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.