我想知道如何通过列的编号而非名称从gridview获取列名。
例如:Name|Age|Birthday(因此name=0,age=1等)
谢谢。
你可以这样获取:
gv.HeaderRow.Cells[i].Text
或者像这样:
gv.Rows[0].Cells[i].Text
Rows[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;
}
}
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;
}
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(); */
这不是问题的答案。只有在您从未更改网格视图中的标题文本时,才是答案。问题的提问者想要通过索引获取数据库字段名称。
我看到了许多“答案”,它们仅提供网格视图中所选行的文本或标题文本,两者都无法回答所提出的问题...
你可能会问为什么?如果您要对系统中的更新进行审计,并希望比较旧值和新值,并且仅在更改时更新并希望指示循环的索引处更新了哪个字段,该怎么办?
例如:
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
所以问题是,如何通过代码获取数据库表字段名称的索引?我也一直在寻找答案,但我看到的所有“答案”都不是我认为我们真正想要的答案。这里提到的所有方法都不是对数据库表字段名称的强有力的引用。