使用GridViewRowEventArgs在循环中访问列名

时间:2014-10-17 12:31:17

标签: c# asp.net gridview

我有一个GridView,它在数据绑定上添加了DataTable中所有值的超链接。它是通过使用“GridViewRowEventArgs”功能实现的。但在这里我必须使用循环中的列名称,我无法做到这一点。请帮帮我。

1 个答案:

答案 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";
    }
}