I decided to write this example because this has been asked many times before at the forums.

As you may know, we cannot "directly" hide AutoGenerateColumns in our codes using the code below:

GridView1.Columns[index].Visible = false;

Why?

This is because auto generated columns are not added in the GridView columns collection.Using the code above will give you "index was out of range error".

In this example I will show the different ways on how to hide specific column in GridView with AutoGenerateColumns set to TRUE.

Option 1:  Using the Cells index

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{

        //Just changed the index of cells based on your requirements

        e.Row.Cells[0].Visible = false;

}

 

Option 2: Looping through GridView Row Controls collections

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{

        //Just changed the index of cells based on your requirements

        foreach (TableRow row in GridView1.Controls[0].Controls)

        {

            row.Cells[0].Visible = false;

        }

}

 

You can use the above options for hiding the columns if you are sure with the order of the columns in the Table. Please note that autogenerated columns will display all the columns from the DataSource, so you must be careful when using index for hiding the columns.

Option 3: Looping through GridView Cells

As you may know the GridView cells are composed of different DataControlFields and basically AutoGenerated fields uses a BoundField for displaying the data. In this case we can loop through the cells generated by the GridView and cast the cell to a DataControlFieldCell type to get the ContainingField then we can cast this ContainingField to a BoundField sothat we can check the DataField used in a particular AutoGenerated BoundField and Hide them using its visible property.

To make it more clearer then you can check this code block below:

rotected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{

   //Just set the Column Name that you wish to hide based on your requirements

        foreach (TableCell cell in e.Row.Cells)

        {

            BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;

            if (field.DataField == "ColumnName")

            {

                field.Visible = false;

            }

        }

}

 

As you can see, we check for the ColumnName first before hiding the column instead of using column indexing.

The ColumnName above indicates the field from your DataSource that you wan’t to hide. You can use this option for hiding the columns if you do not know the sequence of the columns from the DataSource.

That’s it! Hope you will find this example useful!

 

Technorati Tags: ,,,