1

这是我gridview的,当用户单击行内的编辑按钮时触发的事件。出于某种原因,我的datakey值正在使程序崩溃,说它为空。我不知道为什么。中的 DataKeyNamesgridview正是我想要的,formID. gridview这是正确的,因为如您所见, 中的最后一列显示了formID并且它显示得很好。所以我不知道我哪里出错了。

 <asp:GridView ID="gvHistory" runat="server" DataSourceID="ObjectDataSource" 
                AutoGenerateColumns="False" CellPadding="10" CellSpacing="5" 
                CssClass="userHistory" DataKeyNames="formID">
                <Columns>
                    <asp:BoundField DataField="clientName" HeaderText="User" />
                    <asp:BoundField DataField="formName" HeaderText="Form" />
                    <asp:BoundField DataField="dateCreated" HeaderText="Date Created" />
                    <asp:BoundField DataField="dateRevised" HeaderText="Last Revision Date" />
                    <asp:BoundField DataField="dateSubmitted" HeaderText="Date Submitted" />
                    <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:Button ID="edit" runat="server" CausesValidation="false" CommandName="editForm" 
                                Text="Edit" OnDataBinding="btnEdit_DataBinding" OnClick="btnEdit_Click" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:Button ID="delete" runat="server" CausesValidation="false" CommandName=""
                                Text="Delete" OnDataBinding="btnDelete_DataBinding" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="formID" />
                </Columns>
            </asp:GridView>

protected void btnEdit_Click(object sender, System.EventArgs e)
{
    Session["formID"] = gvHistory.SelectedDataKey.Value;
    Label1.Text = Session["formID"].ToString();

}
4

2 回答 2

1

如果您正在使用CommandName您的项目模板,那么您可以简单地使用Row_Command事件,您不需要为按钮单击创建单独的处理程序。

protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "editForm")
    {
      GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
      string value=grdView.DataKeys[row.RowIndex].Values["myDataKey"].ToString();
    }
}
于 2013-04-17T20:18:55.750 回答
0

按钮 btn =(按钮)发送者;

        GridViewRow gvrow = (GridViewRow)btn.NamingContainer;
        if (gvrow != null)
        {
            //Get the Row Index
            int rowIndex = gvrow.RowIndex;
            //Get the DataKey value
            Session["formID"] = gvHistory.DataKeys[rowIndex].Value.ToString();
            Label1.Text = Session["formID"].ToString();

        }
于 2013-04-17T20:15:59.340 回答