How to get column name from gridview?

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

thank.

+5
source share
6 answers

You can do it as follows:

gv.HeaderRow.Cells[i].Text

Or like this:

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

Lines [0] should be your title bar.

+11
source
//// 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;
}
+3
source

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

, ,

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

:

  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;
        }
    }
+2

.... , GridView . colnum .

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;
}
+1

. , gridview. .

"", gridview , ...

, ? , , , , .

:

Protected Sub gv_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
    Dim intValCount As Integer = Integer.Parse(e.NewValues.Count)
    If intValCount > 0 Then
        Dim i As Integer = 0
        For i = 0 To intValCount - 1
            If Not e.OldValues(i).Equals(e.NewValues(i)) Then
                ' values have changed, audit the change
                Sys.Audits.General(intID, "the_database_table", <the table field by index(i)>, e.OldValues(i).ToString, e.NewValues(i).ToString)
            End If
            i += 1
        Next
    End If
End Sub

, , ? , "", , , , , . , , .

0

Its easy: here I read the gridview header text for each header cell and added them as new columns to the data table.

DataTable dt = new DataTable();
foreach(DataControlFieldHeaderCell column in yourGridview.HeaderRow.Cells)
{
  dt.Columns.Add(column.Text.Trim().Replace(" ", ""));                           
}

//Make sure you do all this after yourGridview.DataBind(); 
//If you do not want to bind data first simply bind an empty list like so:
/* yourGridview.DataSource = new List<string>();
   yourGridview.DataBind(); */
0
source

All Articles