How to get row data by clicking a button in a row in an ASP.NET gridview How to get row data by clicking a button in a row in an ASP.NET gridview asp.net asp.net

How to get row data by clicking a button in a row in an ASP.NET gridview


You can also use button click event like this:

<asp:TemplateField>    <ItemTemplate>        <asp:Button ID="Button1" runat="server" Text="Button"                     OnClick="MyButtonClick" />    </ItemTemplate></asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e){    //Get the button that raised the event    Button btn = (Button)sender;    //Get the row that contains this button    GridViewRow gvr = (GridViewRow)btn.NamingContainer;} 

OR

You can do like this to get data:

 void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e) {    // If multiple ButtonField column fields are used, use the    // CommandName property to determine which button was clicked.    if(e.CommandName=="Select")    {      // Convert the row index stored in the CommandArgument      // property to an Integer.      int index = Convert.ToInt32(e.CommandArgument);          // Get the last name of the selected author from the appropriate      // cell in the GridView control.      GridViewRow selectedRow = CustomersGridView.Rows[index];    }}

and Button in gridview should have command like this and handle rowcommand event:

<asp:gridview id="CustomersGridView"         datasourceid="CustomersSqlDataSource"         autogeneratecolumns="false"        onrowcommand="CustomersGridView_RowCommand"        runat="server">        <columns>          <asp:buttonfield buttontype="Button"             commandname="Select"            headertext="Select Customer"             text="Select"/>        </columns>  </asp:gridview>

Check full example on MSDN


Place the commandName in .aspx page

 <asp:Button  ID="btnDelete" Text="Delete" runat="server" CssClass="CoolButtons" CommandName="DeleteData"/>

Subscribe the rowCommand event for the grid and you can try like this,

protected void grdBillingdata_RowCommand(object sender, GridViewCommandEventArgs e){        if (e.CommandName == "DeleteData")        {            GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);            HiddenField hdnDataId = (HiddenField)row.FindControl("hdnDataId");         }}


<ItemTemplate>     <asp:Button ID="Button1" runat="server" Text="Button"             OnClick="MyButtonClick" /></ItemTemplate>

and your method

 protected void MyButtonClick(object sender, System.EventArgs e){     //Get the button that raised the eventButton btn = (Button)sender;    //Get the row that contains this buttonGridViewRow gvr = (GridViewRow)btn.NamingContainer;}