How to delete particular row in grid view in asp.net c#

In this article, I will show you that how we can delete the particular row in the grid view. We will add the link button in the grid view and we will create the click event of the link button.
Sql Server (Data Base):-
Table Design:-



Script the creation of table:-
USE [CodeSolution]
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[reg](
          [id] [int] IDENTITY(1,1) NOT NULL,
          [Name] [nvarchar](50) NULL,
          [Gender] [nvarchar](50) NULL,
          [Email] [nvarchar](50) NULL,
 CONSTRAINT [PK_reg] PRIMARY KEY CLUSTERED
(
          [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO



Data in table:-



Design:-



Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="deleteingridview.aspx.cs" Inherits="deleteingridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>delete button inside the grid view</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="gvdetails" runat="server" AutoGenerateColumns="False" CellPadding="4"
                DataKeyNames="ID" Width="560px" GridLines="None" Font-Names="Times New Roman"
                ForeColor="#333333"  RowStyle-HorizontalAlign="Center">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:BoundField DataField="name" HeaderText="Name" SortExpression="Name" ItemStyle-Width="90px" />
                    <asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender"
                        ItemStyle-Width="90px" />
                    <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email"
                        ItemStyle-Width="90px" />
                    <asp:TemplateField HeaderText="Delete">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkdelete" runat="server" OnClick="lnkdelete_Click" Text="Delete"></asp:LinkButton>
                        </ItemTemplate>


                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#7C6F57" />
                <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
                <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                <PagerStyle ForeColor="White" HorizontalAlign="Center" BackColor="#666666" />
                <RowStyle BackColor="#E3EAEB" />
                <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#F8FAFA" />
                <SortedAscendingHeaderStyle BackColor="#246B61" />
                <SortedDescendingCellStyle BackColor="#D4DFE1" />
                <SortedDescendingHeaderStyle BackColor="#15524A" />
            </asp:GridView>
    </div>
    </form>
</body>
</html>

Code behind(c#):-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class deleteingridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindUserDetails();
    }

    protected void lnkdelete_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtndel = sender as LinkButton;
        GridViewRow gdrow = lnkbtndel.NamingContainer as GridViewRow;
        int fileid = Convert.ToInt32(gvdetails.DataKeys[gdrow.RowIndex].Value.ToString());

        using (SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa; password=12345678"))
        {
            using (SqlCommand cmd = new SqlCommand("", con))
            {
                cmd.CommandText = "delete  from reg where id=@id";
                cmd.Parameters.AddWithValue("@id", fileid);
                cmd.Connection = con;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dataTable = new DataTable();
                dataTable.Load(dr);
                gvdetails.DataSource = dataTable;
                gvdetails.DataBind();
                Response.Write("<script>alert('Record successfully delete')</script>");
                BindUserDetails();
            }
        }
    }

    protected void BindUserDetails()
    {
       


        SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa; password=12345678");
        SqlCommand cmd = new SqlCommand(("select * from reg"), con);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvdetails.DataSource = ds;
            gvdetails.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gvdetails.DataSource = ds;
            gvdetails.DataBind();
            int columncount = gvdetails.Rows[0].Cells.Count;
            gvdetails.Rows[0].Cells.Clear();
            gvdetails.Rows[0].Cells.Add(new TableCell());
            gvdetails.Rows[0].Cells[0].ColumnSpan = columncount;
            gvdetails.Rows[0].Cells[0].Text = "No Records Found";
        }
    }
}

Out-Put:-



How to delete particular row in grid view in asp.net c# How to delete particular row in grid view in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 12:00:00 PM Rating: 5

3 comments:

  1. Con.open(); error gives when login btn click on brouser

    ReplyDelete
  2. Please check your connection string @nitin

    ReplyDelete
  3. محمد الأسمريJuly 29, 2023 at 5:55 AM

    thank you so much

    ReplyDelete

Powered by Blogger.