Reputation: 41
I have added the two button in my gridview.. where data gets loaded in grid view on page load event .. now i want to write the update and delete query on add and delete button respectively. My question is how to select the row id on button click event
<asp:GridView ID="GridView1" runat="server" CssClass="flat-table flat-table-1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_add" runat="server" CommandName="Add" OnClick="btn_add_Click" Text="Add" CssClass="btn btn-align btn-primary" />
<asp:Button ID="btn_cancel" runat="server" CommandName="Cancel" OnClick="btn_cancel_Click" Text="Delete" CssClass="btn btn-align btn-danger" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Upvotes: 0
Views: 2704
Reputation: 7462
Modify ItemTempalate
to following.Note: i have used CommandArgument
to pass selected row_index
.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_add" runat="server" CommandName="Add" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add" CssClass="btn btn-align btn-primary" />
<asp:Button ID="btn_cancel" runat="server" CommandName="Cancel" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Delete" CssClass="btn btn-align btn-danger" />
</ItemTemplate>
</asp:TemplateField>
And add row_command
event, and use following server side code , i have handled for "Add"
operation only.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Add")
{
// Handling for add
string arg = e.CommandArgument.ToString();
int rowidx = int.Parse(arg);
// arg = selected index, as we are using that in cmd arg.
GridViewRow SelectedRow = GridView1.Rows[rowidx];
}
}
Upvotes: 0