R – GridView no column present even after DataBind()

asp.netgridview

I have a DataView that was already populated with data (Verified this to be true).

I then set the DataSource of my GridView to that DataView and called the .DataBind() Function.

Right after binding, I checked the column count of my GridView (grid.Columns.Count) and it shows 0. But it is showing the right output with 15 columns.

Also, accessing a column using its index will throw an exception.

How can I access the column then?

Thanks!

EDIT — Additional Info:

I actually need to add a "glyph" (UP/DOWN arrow) in the column header to show what column are being sorted and its direction. The code below is what I am using. Problem is, the Columns.Count is always zero.

    for (int i = 0; i < dgData.Columns.Count; i++)
    {
        string colExpr = dgData.Columns[i].SortExpression;
        if (colExpr != "" && colExpr == dgData.SortExpression)
            item.Cells[i].Controls.Add(glyph);
    }

Best Answer

Edit

Try this, it's a little fugly as it relies on testing the linkbutton text against the GridView SortExpression. The Gridview ID is "test"

    protected void test_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell tc in e.Row.Cells)
            {
                if(test.SortExpression.Contains( (tc.Controls[0] as LinkButton).Text ))
                    tc.Controls.Add( glyph )
            }
        }
    }

I don't think the columns collection is set if you are auto generating the columns...

You could check the Row.Cells.Count or if you need column names, grab the HeaderRow, and iterate through the Cells & grab their .Text Value.

If the GridView is sortable (e.g. has clickable links in the header, then to get the column names you'll need to check

foreach(Row r in GridView.Rows)
{
    if(r.RowType == HeaderRow)
    {
         r.Cells[0].Controls[0]; //Link Control is here.
    }
}   
Related Topic