Saturday, January 10, 2015

How to Delete Row from Gridview With JavaScript Confirmation in C#, Asp.net

Introduction:

Here I will explain how to delete row from gridview in asp.net using c# , with Java Script confirmation message . when you Click on Delete button it will show you confirmation box to Delete Yes or No.

The below code in your .aspx page


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>ConfirmBox in Gridview Row Delete</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvrecords" CellPadding="5"
DataKeyNames="UserId" AutoGenerateColumns="false" onrowdatabound="gvrecords_RowDataBound">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserId" />
<asp:BoundField DataField="FirstName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="Education" />
<asp:BoundField DataField="LastName" HeaderText="Location" />
<asp:TemplateField HeaderText="Delete" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" OnClick="lnkdelete_Click" OnClientClick="return confirm('Are you sure you want delete');" >
 Delete User 
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


The blow code is aspx.cs code behind file.

using System.Web.UI;using System.Data;using System.Web.UI.WebControls;using System.Text.RegularExpressions;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        {
            BindGridview();
        }
}
protected void BindGridview()
    {
        DataTable dt = new DataTable();       

        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Columns.Add("Location", typeof(string));
        dt.Rows.Add(1, "Muhammed Asad", "BCIT" , "Karachi");
        dt.Rows.Add(2, "Muhammed Ali", "Msc", "Karachi");
        dt.Rows.Add(3, "Madhav Sai", "MS", "Karachi");
        dt.Rows.Add(4, "Asma", "MBA", "Karachi");
        dt.Rows.Add(6, "Faheem Shah", "MBBS", "Karachi");
        dt.Rows.Add(7, "Asif Raza", "B.Tech", "Karachi");
        dt.Rows.Add(8, "Daniel", "CA", "Karachi");
        gvDetails.DataSource = dt;
        gvDetails.DataBind();       
    }

The below is the main JavaScript to show conformation Box.

OnClick="lnkdelete_Click" OnClientClick="return confirm('Are you sure you want delete');" 


Demo 

No comments:

Post a Comment