我有一行数据需要在数据库中使用存储过程进行修改。但为了调用该存储过程,我需要知道每一列的名称。如何确定列的名称?(硬编码不是一种选择,因为我们正在谈论很多名称可能会更改的列)。
编辑:给出接受的答案,看起来 eviljack 想要列的标题文本而不是绑定字段的名称
要获取列的标题文本,您可以使用以下命令:
字符串 colText = grid.Columns[i].HeaderText;
其中 i 是列的索引。
假设您使用的是 BoundField 列,您可以从 GridView 获取 Columns 集合并将(从 DataControlField)转换为 BoundField,获取 DataField 属性
foreach (TableCell objCell in e.Row.Cells)
{
if (objCell is DataControlFieldHeaderCell)
{
string HEADERTEXT = objCell.Text;
}
}
''' <summary>
''' Requires that the 'AccessibleHeaderText' property is set on the column in the aspx
''' </summary>
Private Function GetCellByName(ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs, ByVal colName As String) As System.Web.UI.WebControls.TableCell
Dim result As TableCell = Nothing
If e.Row.RowType = DataControlRowType.DataRow Then
Dim grid As GridView = e.Row.NamingContainer
Dim index As Integer = 0
For i As Integer = 0 To grid.Columns.Count - 1
If String.Compare(grid.Columns(i).AccessibleHeaderText, colName, True) = 0 Then
index = i
Exit For
End If
Next
If index <= e.Row.Cells.Count Then
result = e.Row.Cells(index)
End If
End If
Return result
End Function
List<string> ColName = new List<string>();
foreach(DataColumn c in gridview.Columns)
{
ColName.Add(c);
}