【问题标题】:Programmatically determine column name of GridView controls?以编程方式确定 GridView 控件的列名?
【发布时间】:2010-09-16 22:43:43
【问题描述】:

我有一行数据需要在数据库中使用存储过程进行修改。但为了调用该存储过程,我需要知道每一列的名称。如何确定列的名称? (硬编码不是一种选择,因为我们正在谈论很多名称可能会更改的列)。

编辑:鉴于接受的答案,看起来 eviljack 想要列的标题文本而不是绑定字段的名称

【问题讨论】:

  • 要列的标题文本还是列绑定的数据库字段的名称?

标签: asp.net gridview


【解决方案1】:
List<string> ColName = new List<string>();
foreach(DataColumn c in gridview.Columns)
{
     ColName.Add(c);
}

【讨论】:

  • 你能补充一些解释吗?
【解决方案2】:
''' <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

【讨论】:

    【解决方案3】:
                    foreach (TableCell objCell in e.Row.Cells)
                    {
                        if (objCell is DataControlFieldHeaderCell)
                        {
                            string HEADERTEXT = objCell.Text;
    
                        }
                     }
    

    【讨论】:

      【解决方案4】:

      要获取列的标题文本,您可以使用:

      string colText = grid.Columns[i].HeaderText;

      其中 i 是列的索引。

      【讨论】:

      • 标题文本和数据库列名不一定是同一个东西...
      【解决方案5】:

      假设您使用的是 BoundField 列,您可以从 GridView 获取 Columns 集合并将(从 DataControlField)转换为 BoundField,获取 DataField 属性

      【讨论】:

        猜你喜欢
        • 2011-04-17
        • 2010-11-13
        • 1970-01-01
        • 2023-03-06
        • 2013-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多