Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

But Grid is ok

I can do

for (int i = 0; i < GridView1.HeaderRow.Cells.Count;i++) 

I rename request headers here but

GridView1.Columns[i].Visible = false; 

I can't use it because of GridView1.Columns.Count is 0.

So how can I hide them ?

like image 666
cnd Avatar asked Jan 19 '10 06:01

cnd


People also ask

How to hide column in Grid view ASP net?

The columns->visible property specifies the visibility of a column. To hide a column at the initial rendering, set the columns->visible property to false.

How can hide column in GridView after Databind?

The way to hide a column in a DataBound GridView is to trap the RowCreated Event and set a Cell inside the column of the row to Visible = false.


2 Answers

Try putting the e.Row.Cells[0].Visible = false; inside the RowCreated event of your grid.

protected void bla_RowCreated(object sender, GridViewRowEventArgs e) {     e.Row.Cells[0].Visible = false; // hides the first column } 

This way it auto-hides the whole column.

You don't have access to the generated columns through grid.Columns[i] in your gridview's DataBound event.

like image 176
Jan Jongboom Avatar answered Sep 17 '22 12:09

Jan Jongboom


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);     } } 
like image 41
Steve Hibbert Avatar answered Sep 21 '22 12:09

Steve Hibbert