ASP.NET GridView RowIndex As CommandArgument

前端 未结 9 1611
天涯浪人
天涯浪人 2020-11-30 23:40

How can you access and display the row index of a gridview item as the command argument in a buttonfield column button?



            


        
相关标签:
9条回答
  • 2020-12-01 00:42

    I typically bind this data using the RowDatabound event with the GridView:

    protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
       if (e.Row.RowType == DataControlRowType.DataRow) 
       {
          ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
       }
    }
    
    0 讨论(0)
  • 2020-12-01 00:43

    I think this will work.

    <gridview>
    <Columns>
    
                <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
            </Columns>
    </gridview>
    
    0 讨论(0)
  • 2020-12-01 00:44

    Here is Microsoft Suggestion for this http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

    On the gridview add a command button and convert it into a template, then give it a commandname in this case "AddToCart" and also add CommandArgument "<%# ((GridViewRow) Container).RowIndex %>"

    <asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="AddButton" runat="server" 
          CommandName="AddToCart" 
          CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
          Text="Add to Cart" />
      </ItemTemplate> 
    </asp:TemplateField>
    

    Then for create on the RowCommand event of the gridview identify when the "AddToCart" command is triggered, and do whatever you want from there

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      if (e.CommandName == "AddToCart")
      {
        // Retrieve the row index stored in the 
        // CommandArgument property.
        int index = Convert.ToInt32(e.CommandArgument);
    
        // Retrieve the row that contains the button 
        // from the Rows collection.
        GridViewRow row = GridView1.Rows[index];
    
        // Add code here to add the item to the shopping cart.
      }
    }
    

    **One mistake I was making is that I wanted to add the actions on my template button instead of doing it directly on the RowCommand Event.

    0 讨论(0)
提交回复
热议问题