How to get the cell value by column name not by index in GridView in asp.net

后端 未结 10 1570
轻奢々
轻奢々 2020-12-01 06:21

I am having a gridview in asp.net and now I want the cell value by the column name but not by the cell index.

How would be it possible

相关标签:
10条回答
  • 2020-12-01 06:41

    For Lambda lovers

    protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var boundFields = e.Row.Cells.Cast<DataControlFieldCell>()
                .Select(cell => cell.ContainingField).Cast<BoundField>().ToList();
    
            int idx = boundFields.IndexOf(
                boundFields.FirstOrDefault(f => f.DataField == "ColName"));
    
            e.Row.Cells[idx].Text = modification;        
        }
    }
    
    0 讨论(0)
  • 2020-12-01 06:49

    Based on something found on Code Project

    Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.

    protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (DataTable)((GridView)sender).DataSource;
            int colIndex = dt.Columns["MyColumnName"].Ordinal;
    
            e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
        }
    }
    
    0 讨论(0)
  • 2020-12-01 06:52

    Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.

    public static int GetColumnIndexByName(GridView gridView, string columnName)
        {      
            for (int i = 0; i < gridView.Columns.Count ; i++)
            {
                if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
                {
                    return i;
                }
            }     
            return -1;
        }
    
    0 讨论(0)
  • 2020-12-01 06:54

    Although its a long time but this relatively small piece of code seems easy to read and get:

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
       int index;
       string cellContent;
    
        foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
        {
           if( tc.Text.Equals("yourColumnName") )
           {
             index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
             cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
             break;
           }
        }
    }
    
    0 讨论(0)
提交回复
热议问题