如何从gridview获取列名?

我想知道如何从gridview获取列名? 按其编号而非名称。 喜欢:姓名|年龄|生日:(所以姓名= 0,年龄= 1等…)

谢谢。

你可以这样得到它:

gv.HeaderRow.Cells[i].Text 

或者像这样:

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

行[0]应该是您的标题行。

 //// 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; } 

只是

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

重温这个老问题….可以使用这种代码获取绑定到GridView的数据的字段名称。 这使得colnum和字段名称的字典。

 private static IDictionary GetGridViewFieldNames(object grid) { var names = new Dictionary(); 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; } 

这不是问题的答案。 如果您从未更改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", , e.OldValues(i).ToString, e.NewValues(i).ToString) End If i += 1 Next End If End Sub 

那么问题是如何通过代码隐藏索引获取数据库表字段名称? 我也一直在寻找这个,我见过的所有“答案”都不是我认为我们有些人真正想要的答案。 我在这里看到的所有提到的方法都不是对数据库表字段名称的防弹引用。

很简单:在这里,我读取每个标题单元格的gridview标题文本,并将它们作为新列添加到数据表中。

 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(); yourGridview.DataBind(); */