In this article I will demostration how to confirm first before GridViewn RowDeleting. First we need to set up a gridview for this article I have build a gridview having three bound fields ID,Product,Price and one ItemTemplate field Delete. Below is the code for declaring GridView.
<asp:GridView ID="gv_ROD" runat="server" AllowSorting="true"
AutoGenerateColumns="false" CellPadding="4" Width="1034px"
onrowdeleting="lnkbtn_Delete_Click"
onRowDataBound="addConfirm">
<Columns>
<ItemStyle Height="20px" />
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="Id" InsertVisible="False"
SortExpression="ID" />
<asp:BoundField DataField="Product" HeaderText="Product" InsertVisible="False" SortExpression="Product" />
<asp:BoundField DataField="Price" HeaderText="Price" InsertVisible="False" SortExpression="Price" />
<asp:TemplateField HeaderText="Delete" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn_Delete" runat="server" OnClick="lnkbtn_Delete_Click" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In GridView I use onRowDeleting and onRowDataBound Event:
onrowdeleting="lnkbtn_Delete_Click"
onRowDataBound="addConfirm">
Add the following code on source file:
protected void addConfirm(Object src, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = (LinkButton)e.Row.FindControl("lnkbtn_Delete");
string supplier = linkButton.Text.Replace("'", "\\'");
linkButton.Attributes["onClick"] = "javascript:return confirm ( 'Are You Sure You Want To Delete " +
"?' )"; }
}
protected void lnkbtn_Delete_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow row = (GridViewRow)lnkbtn.NamingContainer;
string id = row.Cells[0].Text.ToString();
// Call Delete Query here…
}


Thank you. This was exactly what I needed for a project I am working on.
ReplyDelete