Tuesday, October 25, 2011

Check if GridView Column Exists

If you have a DataRowView you can use the following extension method to check if a GridView column exists:

public static bool ColumnExists( this  DataRowView rowData,  string  fldToCheck)
{

return rowData.Row.Table.Columns.Contains(fldToCheck);
}

Normally, you would use it on RowDataBound event, e.g:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

DataRowView rowData = e.Row.DataItem as DataRowView;
string  fldToCheck = "MyFieldName";
if (e.Row.RowType == DataControlRowType.DataRow)
{
      if (rowData.ColumnExists(fldToCheck) ...


Related posts:
Find GridView Column Index
Set DataRow Values and Other ASP.NET GridView Tips


1 comment:

  1. Cheers for that - very helpful!

    Also for the VB users its possible to it in one line during the RowDataBound event...

    If CType(e.Row.DataItem, DataRowView).Row.Table.Columns.Contains("TableColumnToCheckFor") Then...

    ReplyDelete