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 ?
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.
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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With