How to hide columns in an ASP.NET GridView with auto-generated columns?

前端 未结 12 1674
陌清茗
陌清茗 2020-11-30 08:28

GridView1.Columns.Count is always zero even SqlDataSource1.DataBind();

But Grid is ok

I can do

for (int i = 0; i < GridView1.HeaderRow.Cel         


        
12条回答
  •  萌比男神i
    2020-11-30 08:56

    The Columns collection is only populated when AutoGenerateColumns=false, and you manually generate the columns yourself.

    A nice work-around for this is to dynamically populate the Columns collection yourself, before setting the DataSource property and calling DataBind().

    I have a function that manually adds the columns based on the contents of the DataTable that I want to display. Once I have done that (and then set the DataSource and called DataBind(), I can use the Columns collection and the Count value is correct, and I can turn the column visibility on and off as I initially wanted to.

    static void AddColumnsToGridView(GridView gv, DataTable table)
    {
        foreach (DataColumn column in table.Columns)
        {
            BoundField field = new BoundField();
            field.DataField = column.ColumnName;
            field.HeaderText = column.ColumnName;
            gv.Columns.Add(field);
        }
    }
    

提交回复
热议问题