I am trying to show/hide GridView columns conditionally.
I am creating a dynamic DataTable and then Binding it to the GridView
Later, on a post back, I am ch
GridView.Columns returns a DataControlFieldCollection.
From it's remarks-section:
If you are using the
GridView
orDetailsView
control, theDataControlField
objects that are automatically created (for example, when theAutoGenerateColumns
property istrue
) are not stored in the publicly accessible fields collection. You can only access and manipulate DataControlField objects that are not automatically generated.
From the GridView.Columns remarks section:
Explicitly declared column fields can be used in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields. Automatically generated column fields are not added to the Columns collection.
So only columns added declaratively are accessible in GridView.Columns
. Since you have set AutoGenerateColumns to true
(default) they are not added to the Columns
collection.
If you need the column count you should use your DataSource
. The DataTable
has a Columns property which is initialized even if the table does not contain rows:
int temp = aDT.Columns.Count;
If you set the autogeneratedcolumns
property to true
then the count will always show 0.
From MSDN
The Columns property (collection) is used to store all the explicitly declared column fields that get rendered in the GridView control. You can also use the Columns collection to programmatically manage the collection of column fields.
In your case, you didn't declared your columns explicitly. So you can get columns count like this inside and outside of the Click method if GridView contains at least one row:
Cells Count in a Row = Columns Count.
if(GridView1.Rows.Count>0)
int temp = GridView1.Rows[0].Cells.Count;
Or you can get counts from DataTable inside Click method like that as @TimSchmelter commented:
int temp = aDT.Columns.Count
Change these in ASPX page:
<columns>
tags as below:<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"> <columns> <asp:boundfield datafield="CustomerID" headertext="Customer ID"/> <asp:boundfield datafield="CompanyName" headertext="Company Name"/> <asp:boundfield datafield="Address" headertext="Address"/> <asp:boundfield datafield="City" headertext="City"/> <asp:boundfield datafield="PostalCode" headertext="Postal Code"/> <asp:boundfield datafield="Country" headertext="Country"/> </columns> </asp:GridView>
In .CS file:
int temp = GridView1.Columns.Count; // will return 6