Getting Column Names from RowDataBound

directxBOB
directxBOB used Ask the Experts™
on
I have a RowDataBound event and would like to get the Columns for the Gridview?

My Gridview uses an SQL Datasource and the column headers are generated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
bob,

Have you try this? Since the header generated are link controls:

if(e.Row.Type == DataControlRowType.Header)
{
      foreach (DataControlFieldCell cell in e.Row.Cells)
      {
            foreach (Control ctl in cell.Controls)
                         {
                               LinkButton link = ctl as LinkButton;
                                    if (link != null)
                                    {
                                        string columnheader = link.Text;
                                    }
                       }
      }
}

Hope that help,

Marc
Top Expert 2013
Commented:
If you don;t have sorting enabled there won't be a link button....
You can get header text like:

string header = GridView1.Columns[i].HeaderText; //  i is the 0-based index for the column

Or you can also get it like:

string header = GridView1.HeaderRow.Cells[i].Text;
I agree with sami, I just assume that the sorting in the gridview was on since you sue the autogenerated columns option and probably turn on most of the built-in functionalities.

Marc

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial