views:

211

answers:

2

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.

+1  A: 

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

George
Good info. I like this approach too. +1
tyndall
+3  A: 

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