Saturday, 12 July 2014

GridView - Delete Selected Row Record From DataBase On Button Click in Asp.net Using C#.Net

7/12/2014 - By Pranav Singh 0

GridView is most important in asp.net development. This article will show you how you can delete record from gridview by clicking on button present in itemtemplate of the gridview column.
So for this article first we will create a new asp.net application and add  the new .aspx page in it. After adding new page add a gridview and add new column in grid view not add the button control and after adding button click on button to generate click event of button.
Now your page code will become as shown.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ProjectDemo_Asp.et.Default" %>

<!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>GridView - Delete Selected Row Record From DataBase On Button Click in Asp.net Using C#.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label9" runat="server" Text="" style="font-weight:bold;color:Red;"></asp:Label>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="There are no data records to display."
        Width="100%" BorderStyle="Solid" ShowFooter="True">
        <Columns>
            <asp:TemplateField HeaderText="Id">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("source_numb") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="TITLE">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("title") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("title") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="PUBLISH YEAR">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("publication_year") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("publication_year") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="PRICE">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("retail_price") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("retail_price") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="btndelete" runat="server" Text="Delete"
                        OnClick="btndelete_Click" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <HeaderStyle BackColor="#66CCFF" />       
    </asp:GridView>
   </form>
</body>
</html>

Now we will check the code on our .cs page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
namespace ProjectDemo_Asp.et
{
    public partial class Default : System.Web.UI.Page
    {
        public string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\bookstore.mdb;Persist Security Info=False;";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetDataFromDataBase();
            }
        }

        /// <summary>
        /// Function for binding retribing the data from database
        /// </summary>
        /// <returns></returns>
        public void GetDataFromDataBase()
        {
            DataTable _objdt = new DataTable();
            string querystring = "select * from Books;";
            OleDbConnection _objcon = new OleDbConnection(connectionstring);
            OleDbDataAdapter _objda = new OleDbDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            if (_objdt.Rows.Count > 0)
            {
                GridView1.DataSource = _objdt;
                GridView1.DataBind();
            }
        }
        /// <summary>
        /// This function perform delete record from DB
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int DeleteData(int Id)
        {
            try
            {
                string querystring = "delete from Books where source_numb=" + Id + ";";
                OleDbConnection _objcon = new OleDbConnection(connectionstring);
                OleDbDataAdapter _objda = new OleDbDataAdapter(querystring, _objcon);
                _objcon.Open();
                _objda.SelectCommand.ExecuteNonQuery();
                return 1;
            }
            catch
            {
                return 0;
            }
        }
        /// <summary>
        /// This function is used for getting control value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btndelete_Click(object sender, EventArgs e)
        {
            GridViewRow gvr = ((Button)sender).Parent.Parent as GridViewRow;
            Label lblid = (Label)gvr.FindControl("Label1");
            /*Call delete function*/
           int status= DeleteData(Convert.ToInt32(lblid.Text));
           if (status == 1)
           {
               Label9.Text = "Record delted successfully.";
               /*After deleting record re-bind data*/
               GetDataFromDataBase();
           }
           else
           {
               Label9.Text = "Error while deleting record.";
           }

        }

    }
}

Now I will explain you the above code . in above code first we have retrieved data from database and after that just check the protected void btndelete_Click(object sender, EventArgs e). In this we are detecting the control to find the id. After that we have written the code to delete the selected record.

Now run the application and check the output.


Now click on delete button to delete the record.



 DOWNLOAD

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top