Sukanya
Sukanya

Reputation: 1061

Why column count is 0 for GridView

Friends, I'm populating a GridView in my asp.net application using following code.

    GridView grdExport = new GridView();
    DataSet dsRecord = objHelper.gReturnDataSet(CommandType.Text, strSql);

    grdExport.DataSource = dsRecord.Tables[0];
    grdExport.DataBind();

Now the problem is in immediate window, when I'm checking, I'm getting following result:

    ?dsRecord.Tables[0].Columns.Count
    16
    ?dsRecord.Tables[0].Rows.Count
    37
    ?grdExport.Rows.Count
    37
    ?grdExport.Columns.Count
    0

Please, can anyone tell me why Column count is 0 for grdExport?

Upvotes: 0

Views: 13228

Answers (5)

happyZZR1400
happyZZR1400

Reputation: 2405

May be it is because you didnt place gridView on page? like this:PlaceHolder1.Controls.Add(grdExport)

Upvotes: 1

Niranjan Singh
Niranjan Singh

Reputation: 18290

GridView.Columns Property

Check this:

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.

If you have more columns to your added columns in your grid then it will show count of those columns which you have added not the auto generated columns.

If you show auto generated columns then it will show 0. Check this markup:

 <asp:GridView ID="GridView1" runat="server">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
            </Columns>
        </asp:GridView>

Now it will Show your result of columns's count to 1:
//Before adding column to gridview

?dtResult.Rows.Count
9
?dtResult.Columns.Count
2
?GridView1.Rows.Count
9
?GridView1.Columns.Count
0

After Adding column to gridview.

?GridView1.Columns.Count
1

Upvotes: 1

Abhishek B.
Abhishek B.

Reputation: 5202

It shows the counts = 0 because by default autogenerated columns is true If you add manual colums then it will shows the column counts.
If you write grdExport.AutoGenerateColumns = false; then no columns would rendered in page.

Upvotes: 1

Kishore Kumar
Kishore Kumar

Reputation: 12874

Your GridViewColumn Column will be set after binding your data. So just show a MessageBox.Show to find the column count.

grdExport.AutoGenerateColumns = false;
MessageBox.Show(grdExport.Columns.Count.ToString());

Upvotes: 0

Vishal Patel
Vishal Patel

Reputation: 281

Instead ?grdExport.Columns.Count. This count you get when you add columns collection in gridview at design time. You have to use grdExport.Rows[0].Cells.Count

Upvotes: 0

Related Questions