在按钮命令事件上获取 ASP.NET GridView 中的 DataKey 值

Getting the DataKey Value in ASP.NET GridView on Button command event

Gridview 已配置:

 <asp:GridView ID="gvApptList" runat="server" CssClass="fullwidth" AutoGenerateColumns="False" DataKeyNames="AppointmentID">
                <Columns>
                    <asp:BoundField DataField="Designer" HeaderText="Designer" SortExpression="Designer" />
                    <asp:BoundField DataField="AppointmentDTM" HeaderText="Appointment Date" SortExpression="AppointmentDTM" DataFormatString="{0:MM-dd-yyyy hh:mm tt}" />
                    <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
                    <asp:BoundField DataField="Disposition" HeaderText="Disposition" SortExpression="Disposition" />
                    <asp:BoundField DataField="AppointmentNotes" HeaderText="Appointment Notes" SortExpression="AppointmentNotes" />
                    <asp:ButtonField ButtonType="Button" CommandName="viewAppointment" Text="View" />
                </Columns>
            </asp:GridView>

当我单击 "View" 按钮时,gvApptList_RowCommand 会触发。它的代码是:

If e.CommandName = "viewAppointment" Then
        Dim tApptID As Long
        gvApptList.SelectedIndex = e.CommandArgument
        If IsNumeric(gvApptList.DataKeys(e.CommandArgument).Value) Then
            tApptID = gvApptList.SelectedDataKey.Value
        Else
            Exit Sub
        End If
        tbAppointmentID.Text = tApptID
        DisplayInfo()
    End If

gvApptList.DataKeys(e.CommandArgument).Value 返回时总是一无所获。我在这里错过了什么?我在其他页面上有这个确切的销售代码。

与您的任务相关,在 ASP.NET GridView 控件中使用 DataKeys 的正确语法如下所示(回复:http://www.codeproject.com/Tips/225352/Nesting-GridView-control-in-ASP-NET,用 C# 编写):

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
     // get data key from selected row
     s.SelectParameters[0].DefaultValue =Convert.ToString(((GridView)sender).DataKeys[e.Row.RowIndex].Values["AppointmentID "]);
    }
}

您应该获取与单击的命令 Button 相对应的 Row 的引用,然后从 Row 中提取 DataKeys 值。此外,确保底层 DataSource 在其 SELECT 查询中包含 AppointmentID 字段。

根据您的情况,它可能如下所示(参见清单 2)

清单 2.

protected void ViewButton_OnClick(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow row = btn.NamingContainer as GridViewRow;
    string strID = gvApptList.DataKeys[row.RowIndex].Values["AppointmentID"].ToString();

    int intID;
    if (String.IsNotNullOrEmpty(strID)
    {
      intID = int.Parse(strID);
    }
}

或者您可以使用 TryParse()Convert()

希望这可能有所帮助。