R – GridView ASP.NET – passing a command and a ID to the code-behind

asp.netgridviewnet

What is the correct way to pass a command and an identity Id (int) back to a code behind in ASP.NET. I'm looking at CommandName and CommandArgument. Am I reading it wrong but I think CommandArgument passes back the display index. How does this help?

Can't figure out how I can set CommandArugment to the ID that I need.

Best Answer

Set the CommandName and CommandArgument fields in the GridView then you can access those values in the code behind.

So say you have an image button in every row and when a user selects the button you want to access the command name and parameter for that row.

<asp:GridView ID="gvwRecords" runat="server" DataKeyNames="ID" DataSourceID="objRecords" OnRowCommand="gvwRecords_RowCommand">
  <Columns>
    <asp:TemplateField HeaderImageUrl="~/Images/Approve_Header_Dark.gif">
      <ItemTemplate>
         <asp:ImageButton runat="server" ID="btnApprove" %>' 
          CausesValidation="false" AlternateText="Approve record" ImageUrl="~/Images/Unapproved.gif" 
          CommandName="Approve" CommandArgument='<%# Eval("ID") %>' />
     </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

In the code behind:

protected void gvwRecords_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int recordID = int.Parse(e.CommandArgument.ToString());
    if (recordID > 0)
    {
       switch (e.CommandName.ToLower())
       {
          case "sort":
             break;
          case "approve":
             Record.ApproveRecord(recordID);
             gvwRecords.DataBind();
             break;
           ...
       }
    }
}