BuddyJoe
BuddyJoe

Reputation: 71111

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

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.

Upvotes: 2

Views: 3228

Answers (2)

David Glass
David Glass

Reputation: 2384

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;
           ...
       }
    }
}

Upvotes: 4

George
George

Reputation: 7944

You can get the DataItem associated with that index and get any value you need from it. Here is a linik showing some ways to do this...

http://www.west-wind.com/Weblog/posts/88462.aspx

Upvotes: 1

Related Questions