Search code examples
c#asp.netdatakey

DataKeyValues are null in gridview


Here is my gridview and the event that fires when a user clicks on the edit button within the row. for some reason my datakey value is crashing the program saying it is null. im not sure why. the DataKeyNames in the gridview is exactly what I want it to be, formID. this is correct because the last column in the gridview, as you can see, shows me the formID and it displays just fine. so i have no idea where i am going wrong.

 <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();

}

Solution

  • If you are using CommandName with your item template then You can simply use Row_Command event, you don't need to create separate handler for button click.

    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();
        }
    }