Friday, 5 July 2013

Delete Confirmation box in the asp.net Grid view

Create a page with the gridview in the .aspx page as below

<html>
<head runat="server">

<script type="text/javascript">

function ConfirmationBox(Name) {

var result = confirm('Do you want to delete '+ Name +' Details' );

if (result) {

return true;
}

else {

return false;
}
}
</script>

</head>

<body>

<form id="form1" runat="server">
<div>

<asp:gridview autogeneratecolumns="false" datakeynames="Uid" id="deletegrid" onrowdatabound="deletegrid_RowDataBound" runat="server">

<columns>

<asp:boundfield datafield="Name" headertext="Name"/>
<asp:boundfield datafield="Mobile" headertext="Mobile"/>
<asp:boundfield datafield="Full Name" headertext="Fullname"/>

<asp:templatefield headertext="Delete"/>

<itemtemplate>

<asp:linkbutton id="deltlnkbtn" onclick="deltlnkbtn_Click" runat="server">
Delete User</asp:linkbutton>

</itemtemplate>

</asp:templatefield>

</columns>

</asp:gridview>

</div>
</form>
</body>
</html>
Now enter the following code in the .aspx.cs code behind as
SqlConnection con = new SqlConnection("Data Source=localhostname;Integrated Security=true;Initial Catalog=DBname");

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

BindUser();

}
}

protected void BindUser()
{
//connection open
con.Open();

//sql command to execute query from database
SqlCommand cmd = new SqlCommand("Select * from tablename",con);

cmd.ExecuteNonQuery();

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

//Bind data to gridview
deletegrid.DataSource = ds;
deletegrid.DataBind();

con.Close();
}
protected void deletegrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get the name from a row
string Name =Convert.ToString(DataBinder.Eval(e.Row.DataItem,"Name"));

//identifying the control in gridview
LinkButton lnkbtns = (LinkButton)e.Row.FindControl("deltlnkbtn");

//raising javascript confirmationbox while clicking the link button
lnkbtns.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + Name + "')");
}
}

protected void deltlnkbtn_Click(object sender, EventArgs e)
{

LinkButton lnkbtn= sender as LinkButton;

//get the particular row linkbutton
GridViewRow delgvrow = lnkbtn.NamingContainer as GridViewRow;

//get the userid of particular row
int userid = Convert.ToInt32(deletegrid.DataKeys[delgvrow.RowIndex].Value.ToString());

string Name = gvrow.Cells[0].Text;

con.Open();
SqlCommand cmd = new SqlCommand("delete from UserDetails where Uid="+Uid,con);

int temp=cmd.ExecuteNonQuery();

con.Close();

if (temp == 1)
{

BindUser();

//Displaying alert message after successfully deletion of user
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + Name + " deleted successfully')", true);
}
}

No comments:

Post a Comment

back to top