开发者

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

开发者 https://www.devze.com 2022-12-18 14:41 出处:网络
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 thi开发者_Go百科nk Com

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 thi开发者_Go百科nk 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消