Thursday, October 13, 2011

Find GridView Column Index

If you create GridView columns dynamically using the AutogenerateColumns = true feature, sometimes you need to find a column index from the column name.

I created an extension method to find a column index:

public static int GetIndex(this DataRowView tableData, string fieldName)
        {
            DataColumn dc = tableData.DataView.Table.Columns[fieldName];
            
            if (dc != null)
            {
                return dc.Ordinal;
            }
            return -1;
        }

This is how you call from the RowDataBound event handler:

DataRowView tableData = e.Row.DataItem as DataRowView;
int pos = tableData.GetIndex("MyFieldName");                
if (pos != -1){
   //do your thing
}

No comments:

Post a Comment