我有一个GridView
,它在数据绑定上添加了DataTable
中所有值的超链接。它是通过使用“GridViewRowEventArgs”功能实现的。但在这里我必须使用循环中的列名称,我无法做到这一点。请帮帮我。
答案 0 :(得分:1)
您可以使用此扩展程序:
public static int GetColumnIndex(this GridView grid, string columnName)
{
return grid.Columns.Cast<DataControlField>()
.Select((c, index) => new { Column = c, Index = index })
.Where(x => x.Column.HeaderText.Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.Index)
.DefaultIfEmpty(-1)
.First();
}
然后你可以这样使用它:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grid = (GridView)sender;
int indexOfColumn = grid.GetColumnIndex("ColumnName");
// for example to access the correct index in e.Row.Cells
e.Row.Cells[indexOfColumn].Text = "Hello";
}
}