Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column name from gridview?

Tags:

c#

sql

asp.net

I would like to know how can I get a column name from a gridview? by its number not by name. like : Name|Age|Birthday: ( so name=0 , age=1 etc...)

thanks.

like image 203
Inzi Irina Avatar asked Mar 07 '12 18:03

Inzi Irina


4 Answers

You can get it like this :

gv.HeaderRow.Cells[i].Text

Or like this :

gv.Rows[0].Cells[i].Text

Rows[0] should be your header row.

like image 126
JoRouss Avatar answered Nov 02 '22 21:11

JoRouss


//// Header column names
int gridViewCellCount = yourGridView.Rows[0].Cells.Count;
// string array to hold grid view column names.
string[] columnNames = new string[gridViewCellCount];

for (int i = 0; i < gridViewCellCount; i++)
{
    columnNames[i] = ((System.Web.UI.WebControls.DataControlFieldCell)(yourGridView.Rows[0].Cells[i])).ContainingField.HeaderText;
}
like image 45
user2862491 Avatar answered Nov 02 '22 22:11

user2862491


Revisiting this old question.... it's possible to get the field names of the data bound to a GridView with this kind of code. This makes a dictionary of colnum and field name.

private static IDictionary<int, string> GetGridViewFieldNames(object grid)
{
    var names = new Dictionary<int, string>();
    var view = grid as GridView;
    if (view != null)  {
        for (var i = 0; i < view.Columns.Count; i++)  {
            var field = view.Columns[i] as BoundField;
            if (field != null)  {
                names.Add(i, field.DataField);
            }
        }
    }
    return names;
}
like image 1
O. Jones Avatar answered Nov 02 '22 22:11

O. Jones


simply

 GridView1.Rows[0].Cells[0].Text;

try this if you want to all the cells value from each of the rows

  foreach (GridViewRow r in GridView1.Rows)
    {
        string s = r.Cells[0].Text;
        string y = r.Cells[1].Text;
    }

update:

try this

  foreach (TableCell Tc in GridView1.HeaderRow.Cells)
    {
        //if you are not getting value than find childcontrol of TabelCell.
        string sssb = Tc.Text;
        foreach (Control ctl in Tc.Controls)
        {

            //Child controls
            Label lb = ctl as Label;
            string s = lb.Text;
        }
    }
like image 2
Jignesh Rajput Avatar answered Nov 02 '22 22:11

Jignesh Rajput