Thursday, January 20, 2011

ASP.NET: Hide AutoGenerateColumns in GridView Programmatically

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:

protected 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;
}
}

}

No comments:

Post a Comment