开发者

Determing the row from where the button is selected on grid view asp.net/c#

开发者 https://www.devze.com 2023-02-16 19:47 出处:网络
I have multiple buttons in gridview. How can i determine which particular button on a row has been selected ? How can i capture the row index??

I have multiple buttons in gridview. How can i determine which particular button on a row has been selected ? How can i capture the row index??

I have used

 protected void crtButton_Click(Object sender, EventArgs e)
    {        
            string componentText;
            GridViewRow row = Grid开发者_如何转开发View1.SelectedRow;
            String componentName = row.Cells[1].text;              
     } 

I have tried to generate buttons in gridview .aspx file through following code

         <asp:TemplateField HeaderText="Add to Cart">
                <ItemTemplate>  <asp:Button ID="crtButton" runat="server" Text="Add to Cart" OnClick="crtButton_Click"/>
                </ItemTemplate>                
         </asp:TemplateField>

but it seems like it is not yielding the result. Can any one please help me.

Thank you in anticipation


Here's how you can get the row index of the clicked button:

protected void crtButton_Click(Object sender, EventArgs e)
{
    Button clickedButton = (Button)sender;
    GridViewRow row = (GridViewRow)clickedButton.Parent.Parent;
    int rowIndex = row.RowIndex;
}

However, that's not the greatest approach since you have to know the level of the button. The best approach would be to use OnCommand in conjunction with a CommandArgument.

<ItemTemplate>
    <asp:Button ID="crtButton" runat="server" Text="Add to Cart" OnCommand="crtButton_Command" CommandArgument=<%# Eval("ItemID") %> />
</ItemTemplate>

protected void crtButton_Command(Object sender, CommandEventArgs e)
{
    int itemID = Convert.ToInt32(e.CommandArgument);
}


You can cast the sender to a Button and then look at the attributes of the button:

protected void crtButton_Click(Object sender, EventArgs e)
{
    Button Clicked = sender as Button;
0

精彩评论

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