Reputation: 6152
I have the following gridview
<asp:GridView DataSourceID="odsRooms" DataKeyNames="id,objectid" ID="gvRooms" PageSize="10" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-VerticalAlign="Bottom" HeaderText="Name">
<ItemTemplate>
<%# Eval("title")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbRoomname" MaxLength="20" Text='<%# Bind("title")%>' runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ValidationGroup="updateroom" ShowDeleteButton="true" DeleteText="Delete" ShowEditButton="true" EditText="Edit" CancelText="Cancel" />
</Columns>
</asp:GridView>
Now, everything works nicely, but when the user clicks te delete button in the CommandField row, the item is deleted immediately without asking for confirmation. I wish to add the following attribute to the delete button of the Commandfield: OnClientClick="javascript:return confirm('You sure to delete?');"
How can I do so?
Upvotes: 0
Views: 23607
Reputation: 3864
ASPX
<asp:CommandField HeaderImageUrl="..\Images\DeleteImg.png" ShowDeleteButton="True"
DeleteImageUrl="..\Images\DeleteImg.png" DeleteText="Delete Record"
ItemStyle-Font-Size="8pt" ItemStyle-Width="30px" ButtonType="Image">
</asp:CommandField>
.CS
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
Upvotes: 2
Reputation: 57
you can set delete column to template after that you can use OnClientClick command for return confirm before delete data.
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False"
CommandName="Delete" ImageUrl="~/Delete.png" Text="Delete"
OnClientClick="return confirm('Are you sure to delete data?');" />
</ItemTemplate>
Upvotes: 3
Reputation: 6123
Use the follwoing code
protected void gvRooms_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = (LinkButton)e.Row.Cells[1].Controls[1];
if( lb != null )
{
lb.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record ')");
}
}
}
Upvotes: 5