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

后端 未结 10 1590
轻奢々
轻奢々 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: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");
        }
    }
    

提交回复
热议问题