How to find Grid view button click event?

10,480

Define the button in your grid view markup and assign a CommandName value to the button, like this:

<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server"  
        OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="Add Record">
            <ItemTemplate>
                <asp:Button ID="btnAddRecord"  
                            CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" 
                            CommandName="AddRecord" runat="server" Text="Add" />
            </ItemTemplate>
        </asp:TemplateField> 
    </Columns>
</asp:GridView>

Now in your code-behind, you can handle the OnRowCommand event and AddRecord command, like this:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "AddRecord")
    {
        // Get index of row passed as command argument
        int index = Convert.ToInt32(e.CommandArgument.ToString());

        // Your logic here
    }
}
Share:
10,480

Related videos on Youtube

Jagadisha B S
Author by

Jagadisha B S

I don't know But Sure I am following my dream

Updated on June 26, 2022

Comments

  • Jagadisha B S
    Jagadisha B S almost 2 years
    Button btnAddrecord = (Button)sender;
    GridViewRow gvr =(GridViewRow)btnAddrecord.NamingContainer;
    if (btnAddrecord.CommandName == "onAddMaterial")
    
    • शेखर
      शेखर over 10 years
      kindly provide more details for the question?

Related