Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView Column.Count is always 0 after databind with a datatable

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 checking condition and want to show/hide a few columns of the GridView, but Column.Count is alway 0!

The code I have is as below - ASPX page

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

.CS Page

 protected void Button1_Click(object sender, EventArgs e)
{
   DataTable aDT = new DataTable()
   aDT = createDataTable();   //datatable has 21 columns

   GridView1.DataSource = aDT;
   GridView1.DataBind();

   int temp = GridView1.Columns.Count;   //always 0
}

Not sure what is wrong with the code

like image 844
user1889838 Avatar asked Mar 24 '14 15:03

user1889838


2 Answers

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
like image 67
Farhad Jabiyev Avatar answered Oct 19 '22 02:10

Farhad Jabiyev


GridView.Columns returns a DataControlFieldCollection.

From it's remarks-section:

If you are using the GridView or DetailsView control, the DataControlField objects that are automatically created (for example, when the AutoGenerateColumns property is true) 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;   
like image 44
Tim Schmelter Avatar answered Oct 19 '22 00:10

Tim Schmelter