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

前端 未结 12 1692
陌清茗
陌清茗 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条回答
  •  不知归路
    2020-11-30 09:15

    I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.

    In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.

    For example: A Gridview is on the page as follows.

    
    
    

    And then in the code behind a PopulateGridView routine is called during the page load event.

    protected void PopulateGridView()
    {
        DataTable dt = GetDataSource();
        gv.DataSource = dt;
        foreach (DataColumn col in dt.Columns)
        {
            BoundField field = new BoundField();
            field.DataField = col.ColumnName;
            field.HeaderText = col.ColumnName;
            if (col.ColumnName.EndsWith("ID"))
            {
                field.Visible = false;
            }
            gv.Columns.Add(field);
        }
        gv.DataBind();
    }
    

    In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.

提交回复
热议问题