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

后端 未结 10 1612
轻奢々
轻奢々 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:38

    A little bug with indexcolumn in alexander's answer: We need to take care of "not found" column:

    int GetColumnIndexByName(GridViewRow row, string columnName)
    {
        int columnIndex = 0;
        int foundIndex=-1;
        foreach (DataControlFieldCell cell in row.Cells)
        {
            if (cell.ContainingField is BoundField)
            {
                if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
                {
                    foundIndex=columnIndex;
                    break;
                }
            }
            columnIndex++; // keep adding 1 while we don't have the correct name
        }
        return foundIndex;
    }
    

    and

    protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int index = GetColumnIndexByName(e.Row, "myDataField");
            if( index>0)
            {
                string columnValue = e.Row.Cells[index].Text;
            }
        }
    }
    

提交回复
热议问题