21 Jan 2010

ASP.NET GridRow - Get Cell when you don't know the index - using HeaderText, DataField, SortExpression etc.

Sometimes you want to reference a cell in a gridview row, but you don't know its ordinal index, so Row.Cells[x] is no good for you. In this circumstance it would be nice to say something like "just get me the cell from the column with the HeaderText value 'Price'".

Voila:


public static int GetCellIndexByFieldHandle(this GridView grid, string fieldHandle)
{
int iCellIndex = -1;

for (int iColIndex = 0; iColIndex < grid.Columns.Count; iColIndex++)
{
if (grid.Columns[iColIndex] is DataControlField)
{
DataControlField col = (DataControlField)grid.Columns[iColIndex];
if ((col is BoundField && string.Compare(((BoundField)col).DataField, fieldHandle, true) == 0)
|| string.Compare(col.SortExpression, fieldHandle, true) == 0
|| col.HeaderText.Contains(fieldHandle))
{
iCellIndex = iColIndex;
break;
}
}
}
return iCellIndex;
}


Usage:


void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cellPrice = e.Row.Cells[e.Row.GetCellIndexByFieldHandle('Price')];
}
}


The method works for column HeaderText, DataField and SortExpression, so you should always have a way to grab hold of that cell. One caveat - it can't reference AutoGenerated columns. They have to be defined in the GridView template a la:


<Columns>
<asp:BoundField DataField="Price" />
</Columns>


or


<Columns>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!