简体   繁体   中英

How to know in which row a button is clicked in asp.net gridView

This is a simple gridView I m using in aspx web page

     <asp:GridView ID="Order" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="none"
    ItemType="MyProject.Models.TempList" SelectMethod="GetList" >   
    <Columns>
        <asp:BoundField DataField="ItemID" HeaderText="ID" SortExpression="ItemID" />

        <asp:TemplateField   HeaderText="ItemName">  
            <ItemTemplate>
                <asp:Label runat="server" ID="ItemName" Width="40" Visible="true" text="<%#: Item.Item.ItemName %>"></asp:Label>  
            </ItemTemplate>                      
        </asp:TemplateField>

        <asp:TemplateField   HeaderText="Price(each)">  
            <ItemTemplate>
                <%#: String.Format("{0:c}", Convert.ToDouble(Item.Item.UnitPrice))%>                    
            </ItemTemplate>                         
        </asp:TemplateField>                                                                 

        <asp:TemplateField HeaderText="Delete">            
            <ItemTemplate>
                <div style="float:left">               
             <asp:Button ID="DeleteBtn" runat="server" Text="Delete" OnClick="DeleteBtn_Click"/>                           
            </ItemTemplate>        
        </asp:TemplateField>              
    </Columns>  

</asp:GridView>

I have 2+ items in a list<> which is populating the gridView, how can I tell (in the codeBehind.cs) that which Row the "DeleteBtn" was clicked on?

I was using a for loop to iterate every item in gridView using Rows[i] and used a check box to know which item wants to be deleted using a Update button.

But I want to do it directly on a custom created deletebutton.

Thanks in advance, I know I'm missing something silly.

The best way to do that is using CommandName and CommandArgument in your button declaration like that

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

you can pass any value in the case we pass the rowIndex, you can get a propertie from your object like that CommandArgument="<%# Eval("id") %>" after that you will handle the onRowCommand method

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

  }

hope it helps :)

Use the button's CommandArgument property; assign Container.DataItemIndex to it. Then use the OnRowCommand event of the gridview and grab the index.

Sample aspx:

<asp:Label runat="server" ID="lblMsg" />
<asp:GridView runat="server" id="gvSample" AutoGenerateColumns="false" OnRowCommand="PerformOperation">
    <Columns>
        <asp:BoundField DataField="RowValue"/>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button Text="Delete" runat="server" CommandName="MyCustomCommand" CommandArgument="<%# Container.DataItemIndex %>" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PopulateGrid();
    }
}

private void PopulateGrid()
{
    gvSample.DataSource = Enumerable.Range(0, 10).Select(i => new { RowValue = i });
    gvSample.DataBind();
}

protected void PerformOperation(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "MyCustomCommand")
    {
            var rowIndex = int.Parse(e.CommandArgument);
            lblMsg.Text = string.Format("Button on row index: {0} was clicked!", rowIndex);
    }
}

Let the button field be given a CommandName , say for example a unique string myCommandName in the Edit columns dialog box. Don't worry about the CommandArgument . Then, in the Grid view Row command event, you can check which button (ie column) is clicked by tracing the command name like if e.commandname = "mycommandname" , at the same time the CommandArgument will also be available as String and all we have to do is to converttoint32, something like intSelectedRow = convert.ToInt32(e.CommandArgument) which will give us the selected row's index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM