Tuesday, December 16, 2008

Confirmation for Delete Button in GridView

I am displaying student table in GridView. 'sno' is the primarykey for the student table.
That is why Iam binding that value to CommandArgument of the Button.This can be used in code part
as 'e.CommandArgument' which is also explained later.

The Source Code in GridView is as shown below:

<Columns>

<asp:BoundField HeaderText="SNO" DataField="sno" />
<asp:BoundField HeaderText="NAME" DataField="sname" />
<asp:BoundField HeaderText="CITY" DataField="city" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" CommandArgument='&lt%#Eval("sno") %&gt' OnClientClick="javascript:return fun();"/&gt
</ItemTemplate>
</asp:TemplateField>

</Columns>

Write JavaScript code below in Head Part:

&ltscript type="text/javascript" language="javascript">
function fun()
{
if (confirm("Do u want to really Delete?")==true)
return true
else
return false
}
</script>

In the GridView RowCommand Event , you will write the code for deleting the record.
The code will be as shown below:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string squery = "delete blog_student where sno=" + e.CommandArgument.ToString();
SqlCommand cmd = new SqlCommand(squery, con);
con.Open();
cmd.ExecuteNonQuery();
GetStudentData();
}
}

No comments: