Delete record from gridview on RowCommand Event in asp.Net(c#& vb.net).

Aman Sharma
0
Introduction:
In this article I will explain how to delete row in gridview on Row_Command Event of gridview .


Add a gridview on webpage and add columns which we want to show on the webpage using boundfields of gridview. Now add Template field and add one link button inside template field. Set command-name and command argument. Bind gridview with data from database.
Now use GridView1_RowCommand event of the grid view and also fire RowDeleteing event to handle delete command. Write the code in RowCommand event to delete record.


Implementation: Follow following steps
1.     Create a database i.e. “Blog”.  Then create a table “Student_Info”.
Column Name
Datatype
Student_id
Int(Primary Key. So set Is Identity=True)
Student_Name
Varchar(500)
Age
int
Class
Varchar(50)

2.     Now insert some data in this table using “insert” command.
INSERT INTO student_info(Student_Name,Age,Class) VALUES('Akhsay',12, 'first')
INSERT INTO student_info(Student_Name,Age,Class) VALUES('Raghav',25, 'M.Sc')
INSERT INTO student_info(Student_Name,Age,Class) VALUES('aksht', 23, 'Bsc')
INSERT INTO student_info(Student_Name,Age,Class) VALUES('ankit', 23, 'MBA')
INSERT INTO student_info(Student_Name,Age,Class) VALUES('anil', 23, 'MCA')

3.     Create Connection: Now create connection in  webcofig file as given below.
<connectionStrings>
    <add name="con" connectionString="Data Source=localhost; Initial Catalog= Blog; Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

4.     ASP.Net Page design: Add gridview control on the webpage

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
            CellPadding="3" Width="270px" onrowcommand="GridView1_RowCommand"
            onrowdeleting="GridView1_RowDeleting">
            <Columns>
                <asp:BoundField DataField="Student_name" HeaderText="Student Name" />
                <asp:BoundField DataField="Age" HeaderText="Age" />
                <asp:BoundField DataField="Class" HeaderText="Class" />
                <asp:TemplateField HeaderText="Delete" ShowHeader="False">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False"
                            CommandName="Delete" OnClientClick="javascript: return confirm('Do you want to delete this record?')" CommandArgument='<%#bind("Student_id") %>' Text="Delete"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
            <RowStyle ForeColor="#000066" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#007DBB" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#00547E" />
        </asp:GridView>



5.     ASP.NET code behind File using C#:

In code behind, add following code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Now Fetch data and bIND TO GRIDVIEW
    //Fetch data from database and bind to gridview
    public void Bind_grid()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        DataTable dt = new DataTable();
        SqlDataAdapter dataadapater = new SqlDataAdapter("Select * from student_info", con);
        dataadapater.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

Now Delete Record on RowCommand Event:  Also use event GridView1_RowDeleting to handle delete command
  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int studentid =Convert.ToInt32( e.CommandArgument.ToString());
        if (e.CommandName =="Delete")
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "Delete from student_Info where student_id=" + studentid + "";
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();

            Bind_grid();
        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }


VB.NET code behind file:
In code behind, add following code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Now Fetch data and bIND TO GRIDVIEW:

Partial Public Class gridview
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            Bind_grid()
        End If
    End Sub
    'Fetch data from database and bind to gridview
    Public Sub Bind_grid()
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)
        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        con.Open()
        Dim dt As New DataTable()
        Dim dataadapater As New SqlDataAdapter("Select * from student_info", con)
        dataadapater.Fill(dt)
        GridView1.DataSource = dt
        GridView1.DataBind()
    End Sub
End Class

Now Write Following Code on gridview_Rowcommand event to delete Record:

Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
    Dim studentid As Integer = Convert.ToInt32(e.CommandArgument.ToString())
    If e.CommandName = "Delete" Then
        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        con.Open()
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandText = "Delete from student_Info where student_id=" + studentid + ""
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        con.Close()

        Bind_grid()
    End If
End Sub
Protected Sub GridView1_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)

End Sub



Demo:



Use this code, create your own application and check result. You can use this code in any application by customizing it. If you have any doubt, you can ask by commenting in comment section.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !