Gridview AutoGeneratingColumn事件?

时间:2012-10-16 06:49:36

标签: asp.net gridview datagrid

.NET DataGrid控件有一个AutoGeneratingColumn事件,在更改数据源后立即为每个绑定数据项触发一次。这很有用,因为您可以在模板中定义某些列,如下所示:

<Columns>
        <asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="ww{0}" DataTextField="ID" DataTextFormatString="{0}" HeaderText="ID" />
</Columns>

然后阻止在从数据源自动生成列时复制相同的列。在此示例中,您可以阻止ID列自动生成,如下所示:

Private Sub DG_AutoGeneratingColumn(ByVal sender As Object, ByVal e As DataGridAutoGeneratingColumnEventArgs)
    Dim headername As String = e.Column.Header.ToString()
    If headername = "ID" Then
        e.Cancel = True
    End If
End Sub

我的问题是,使用GridView控件是否可以实现类似的功能。

详情

gridview的数据源是一个DataTable对象,我这样绑定它:

    GridView1.DataSource = results.Tables("Vitals")
    GridView1.DataBind()

我的DataTable中的列数会有所不同,这就是我使用AutoGenerateColumns非常方便的原因。

1 个答案:

答案 0 :(得分:0)

为此,您应该处理RowCreated事件并编写如下内容:

private List<int> hideColumnsIndexes = new List<int>(); 

protected void Page_Load(object sender, EventArgs e)
{
    hideColumnsIndexes.Clear();
}

protected void GridView1_OnRowCreated(object sender, GridViewRowEventArgs e)
{
    //Find indexes
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++ )
        {
            if (e.Row.Cells[i].Text == "Id")
            {
                hideColumnsIndexes.Add(i);
            }

            //Add more columns to hide
        }
    }

    //Hide cells
    foreach (var index in hideColumnsIndexes)
    {
        e.Row.Cells[index].Visible = false;
    }
}