Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Delete Row from Asp.net Gridview With Confirmation in C#, VB.NET

Nov 26, 2014
Introduction

Here I will explain how to delete or remove row from gridview in
asp.net using c# , vb.net with confirmation message or delete gridview rows with confirmation box in asp.net using c# , vb.net or delete row from gridview with button click in asp.net using c# , vb.net.

Description:
  
In previous articles I explained
sql injection attacks prevention in asp.net, ExecuteReader example in asp.net, import data from excel to sql database in asp.net, export gridview data to excel in asp.net using c# , export gridview data to pdf in asp.net using c# and many articles relating to asp.net, c#,vb.net and jQuery. Now I will explain how to remove row from gridview in asp.net using c# , vb.net with confirmation message.

Before implement this example first design one table UserDetails in your database as shown below

Column Name
Data Type
Allow Nulls
UserId
Int(IDENTITY=TRUE)
Yes
UserName
varchar(50)
Yes
FirstName
varchar(50)
Yes
LastName
varchar(50)
Yes
Once table created in database enter some dummy data to test application after that write the following 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>
<script type="text/javascript">
function ConfirmationBox(username) {
var result = confirm('Are you sure you want to delete '+username+' Details' );
if (result) {
return true;
}
else {
return false;
}
}
</script>
</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="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField HeaderText="Delete User Details">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" OnClick="lnkdelete_Click">Delete User</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Now open code behind file and write the following code

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DeleteGridviewRows : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUserDetails();
        }
    }
    protected void BindUserDetails()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Select * from UserDetails", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            con.Close();
        }
        gvrecords.DataSource = dt;
        gvrecords.DataBind();
    }
    protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //getting username from particular row
            string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
            LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkdelete");
            lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
        }
    }
    protected void lnkdelete_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        //getting particular row linkbutton
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        //getting userid of particular row
        int userid = Convert.ToInt32(gvrecords.DataKeys[gvrow.RowIndex].Value.ToString());
        int result;
        using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + userid, con);
            result = cmd.ExecuteNonQuery();
            con.Close();
        }
        if (result == 1)
        {
            BindUserDetails();
        }
    }
}
VB.NET


Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Partial Class VBCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindUserDetails()
        End If
    End Sub
    Protected Sub BindUserDetails()
        Dim dt As New DataTable()
        Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
            con.Open()
            Dim cmd As New SqlCommand("Select * from UserDetails", con)
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            con.Close()
        End Using
        gvrecords.DataSource = dt
        gvrecords.DataBind()
    End Sub
    Protected Sub gvrecords_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            'getting username from particular row
            Dim username As String = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"))
            Dim lnkbtnresult As LinkButton = DirectCast(e.Row.FindControl("lnkdelete"), LinkButton)
            lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" & username & "')")
        End If
    End Sub
    Protected Sub lnkdelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
        'getting particular row linkbutton
        Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
        'getting userid of particular row
        Dim userid As Integer = Convert.ToInt32(gvrecords.DataKeys(gvrow.RowIndex).Value.ToString())
        Dim result As Integer
        Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
            con.Open()
            Dim cmd As New SqlCommand("delete from UserDetails where UserId=" & userid, con)
            result = cmd.ExecuteNonQuery()
            con.Close()
        End Using
        If result = 1 Then
            BindUserDetails()
        End If
    End Sub
End Class
Demo

Delete Row from Asp.net Gridview With Confirmation in C#, VB.NET


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

0 comments :

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.