I have a GridView
in a ASP.NET web application, in which I have added two buttons in each row:
<ItemTemplate> <asp:Button ID="btnEdit" Text="Edit" runat="server" /> <asp:Button ID="btnDelete" Text="Delete" runat="server"/> </ItemTemplate>
Now how I can get the row data from gridview simply by clicking an edit button in a row?
The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.
The RowCommand Event can be used to get the selected GridView Row value or text. GridView. RowCommand Event: The RowCommand Event occurs when a button is clicked in a GridView control. <asp:GridView OnRowCommand="GridViewCommandEventHandler" />
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; }
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With