Gridview with delete button in asp.net

image

Gridview with delete button in asp.net

Its pretty simple to put buttons in Gridview control.

First design of the page :

Open the .aspx page and add the Gridview control as below :


 <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="datagridview" CssClass="mydatagrid" AllowPaging="True"
            CellPadding="4" ForeColor="#333333" GridLines="None" BorderColor="#003300" BorderStyle="Solid"
            BorderWidth="1px" Font-Size="11pt" Font-Names="Century" OnPageIndexChanging="datagridview_PageIndexChanging"
            OnRowCommand="datagridview_RowCommand" OnRowDeleting="datagridview_RowDeleting">
            <RowStyle BackColor="#EFF3FB" BorderColor="Black" BorderWidth="1px" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" />
            <AlternatingRowStyle BackColor="White" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" />
            <Columns>
                <asp:ButtonField ButtonType="Button" HeaderText="Delete" Text="Delete" CommandName="Delete"
                    ControlStyle-BackColor="#507CD1" ControlStyle-ForeColor="White" ControlStyle-Font-Size="15px" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:Label runat="server" Text=" " ID="lblname"
            ForeColor="#507CD1" Font-Size="20px"></asp:Label>
    </div>
    </form>

Its with design

CODING PART

Open your Web.config file and define your connectionString :


<connectionStrings>
    <add name="myconnectionString" connectionString="Data Source=HITESH\SQLEXPRESS;Initial Catalog=MyDatabase;User ID=hitesh;Password=789"/>
</connectionStrings>

Open code file .cs file
and write the code to fill the GridView

public void fillDataGrid()
    {
        con = new SqlConnection(myconnectionString);
        cmd = new SqlCommand("select * from mytable", con);
        con.Open();
        adapter = new SqlDataAdapter(cmd);
        ds = new DataSet();
        adapter.Fill(ds, "mytable");
        datagridview.DataSource = ds.Tables[0];
        datagridview.DataBind();
        con.Close();
    }

Call this method on PageLoad event

protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)   // make sure to write this to avoid reload of whole page
       {
           fillDataGrid();
       }
 
   }

Add the code for Paging event :

protected void datagridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        datagridview.PageIndex = e.NewPageIndex;
        fillDataGrid();
    }

Now for the Delete button click event (Row commands for gridview):

protected void datagridview_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            int rowno = Int32.Parse(e.CommandArgument.ToString());
            try
            {
                string ProductID = datagridview.Rows[rowno].Cells[1].Text.ToString();
                con = new SqlConnection(myconnectionString);
                cmd = new SqlCommand("Delete from mytable where ID='" + ProductID + "'", con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                lblname.Text = "Deleted Successfully.";
                fillDataGrid();
            }
            catch (Exception ex)
            {
                lblname.Text = ex.Message.ToString();
                fillDataGrid();
            }
        }
    }
    protected void datagridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
// this is important
    }

Now run the page :

image

image


If you like my work, please click the like button and like my page on facebook. You can also comment below…I will try my best to help you out

Here’s the full code for your reference :

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.Sql;
using System.IO;
using System.Text;


public partial class GridViewDeleteButton : System.Web.UI.Page
{
    String myconnectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
    SqlConnection con;
    SqlDataAdapter adapter;
    DataSet ds;
    SqlCommand cmd;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fillDataGrid();
        }
        
    }
    public void fillDataGrid()
    {
        con = new SqlConnection(myconnectionString);
        cmd = new SqlCommand("select * from mytable", con);
        con.Open();
        adapter = new SqlDataAdapter(cmd);
        ds = new DataSet();
        adapter.Fill(ds, "mytable");
        datagridview.DataSource = ds.Tables[0];
        datagridview.DataBind();
        con.Close();
    }
    protected void datagridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        datagridview.PageIndex = e.NewPageIndex;
        fillDataGrid();
    }
    protected void datagridview_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            int rowno = Int32.Parse(e.CommandArgument.ToString());
            try
            {
                string ProductID = datagridview.Rows[rowno].Cells[1].Text.ToString();
                con = new SqlConnection(myconnectionString);
                cmd = new SqlCommand("Delete from mytable where ID='" + ProductID + "'", con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                lblname.Text = "Deleted Successfully.";
                fillDataGrid();
            }
            catch (Exception ex)
            {
                lblname.Text = ex.Message.ToString();
                fillDataGrid();
            }
        }
    }
    protected void datagridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    
}


1 thought on “Gridview with delete button in asp.net”

  1. Pingback: ASP.NET GridView Export to CSV File • ParallelCodes();

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.