Click here to Skip to main content
15,867,330 members
Articles / Web Development / ASP.NET
Article

Edit and Delete multiple Data in DataGrid in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.08/5 (12 votes)
18 Apr 2007 95K   2.5K   41   6
Edit and Delete multiple Data in DataGrid in ASP.NET

Download MultipleDeletionDatagrid.zip - 22.7 KB

Screenshot - datagrid2.jpg

Screenshot - editGrid.jpg

Introduction

I found it very common assignment to make a datagrid with multiple deletion option like HOTMAIL ..and that inspires me to write this code.Here is the code for editing and deleting multiple data with datagrid.

Background

(Optional) Is there any background to this article that may be useful such as an introduction to the basic ideas presented?

Using the code

To use this code just unzip the file as I have not attached the whole project file so you need to add the pages in your project. and some modification as you always need.

Blocks of code should be set as style "Formatted" like this:

//
// Any source code blocks look like this
// 
 
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Configuration;

namespace DelhiApp.Testing
{
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button Button2;
        protected System.Web.UI.WebControls.DataGrid DataGrid2;
        protected System.Web.UI.WebControls.Panel Panel3;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                BindData(DataGrid2);
                Button2.Attributes.Add("onclick","return confirm('Are you sure you wish to delete these records?');");
            }
        }

        private void BindData(DataGrid DataGrid1)
        {
            
            OleDbConnection con=new OleDbConnection(ConfigurationSettings.AppSettings["connectionString"]);
            OleDbCommand cmd=new OleDbCommand();
            cmd.CommandText="select * from emp";
            cmd.Connection=con;
            cmd.Connection.Open();
            OleDbDataReader dr=cmd.ExecuteReader();
            DataGrid1.DataSource=dr;
            DataGrid1.DataBind();
            cmd.Connection.Close();
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {    
            this.Button2.Click += new System.EventHandler(this.Button2_Click);
            this.DataGrid2.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.Cancel_Grid);
            this.DataGrid2.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.Edit_Grid);
            this.DataGrid2.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.Update_Grid);
            this.DataGrid2.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.Delete_Grid);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void Button2_Click(object sender, System.EventArgs e)
        {
            foreach(DataGridItem objItem in DataGrid2.Items)
            {
                if (objItem.ItemType != ListItemType.Header && objItem.ItemType != ListItemType.Footer && objItem.ItemType != ListItemType.Pager)
                {    
                    
                    if(((CheckBox)objItem.Cells[0].FindControl("cbSelected")).Checked == true)
                    {
                        OleDbConnection con=new OleDbConnection(ConfigurationSettings.AppSettings["connectionString"]);
                        OleDbCommand cmd=new OleDbCommand();
                        cmd.CommandText="DELETE from emp where empId=@empId";
                        cmd.Parameters.Add("@empId",OleDbType.Numeric).Value=DataGrid2.DataKeys[objItem.ItemIndex];
                        cmd.Connection=con;
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();
                        cmd.Connection.Close();
                        
                    }
                }
            }
            BindData(DataGrid2);
        }

        private void Delete_Grid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            OleDbConnection con=new OleDbConnection(ConfigurationSettings.AppSettings["connectionString"]);
            OleDbCommand cmd=new OleDbCommand();
            cmd.CommandText="DELETE from emp where empId=@empId";

            
            cmd.Parameters.Add("@empId",OleDbType.Numeric).Value=DataGrid2.DataKeys[e.Item.ItemIndex];

            cmd.Connection=con;
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            DataGrid2.EditItemIndex=-1;
            BindData(DataGrid2);
        }

        private void Edit_Grid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            DataGrid2.EditItemIndex = e.Item.ItemIndex;
            
            // Always bind the data so the datagrid can be displayed.
            BindData(DataGrid2);
        }

        private void Update_Grid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            OleDbConnection con=new OleDbConnection(ConfigurationSettings.AppSettings["connectionString"]);
            OleDbCommand cmd=new OleDbCommand();
            cmd.CommandText="UPDATE emp SET empName=@empName, salary=@salary, joiningDate=@joiningDate where empId=@empId";

            cmd.Parameters.Add("@empName",OleDbType.Char).Value=((TextBox)e.Item.Cells[1].Controls[0]).Text;
            cmd.Parameters.Add("@salary",OleDbType.Numeric).Value=((TextBox)e.Item.Cells[2].Controls[0]).Text;
            cmd.Parameters.Add("@joiningDate",OleDbType.Date).Value=((TextBox)e.Item.Cells[3].Controls[0]).Text;
            cmd.Parameters.Add("@empId",OleDbType.Numeric).Value=DataGrid2.DataKeys[e.Item.ItemIndex];

            cmd.Connection=con;
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            DataGrid2.EditItemIndex=-1;
            BindData(DataGrid2);
        }

        private void Cancel_Grid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            DataGrid2.EditItemIndex = -1;
            BindData(DataGrid2);
        }
    }
}
 
<a href="Edit_and_Delete_Data/MultipleDeletionDatagrid.zip">Download MultipleDeletionDatagrid.zip - 22.7 KB</a>

Remember to set the Language of your code snippet using the Language dropdown.

Use the "var" button to to wrap Variable or class names in <code> tags like this.

Points of Interest

Did you learn anything interesting/fun/annoying while writing the code? Did you do anything particularly clever or wild or zany?

History

Keep a running update of any changes or improvements you've made here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer TATA Communications
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionstoring webform data in pdf file in asp.net Pin
Rambabukasiboina2-Aug-07 4:22
Rambabukasiboina2-Aug-07 4:22 
AnswerRe: storing webform data in pdf file in asp.net Pin
rahul_bit2-Aug-07 19:07
rahul_bit2-Aug-07 19:07 
GeneralTry with ASP.NET 2.0 GridView Pin
Jaiprakash M Bankolli12-Apr-07 20:52
Jaiprakash M Bankolli12-Apr-07 20:52 
GeneralNot able to run the appliaction Pin
honeyss26-Mar-07 1:38
honeyss26-Mar-07 1:38 
GeneralRe: Not able to run the appliaction Pin
rahul_bit26-Mar-07 19:00
rahul_bit26-Mar-07 19:00 
GeneralRe:Thanks Pin
honeyss27-Mar-07 18:24
honeyss27-Mar-07 18:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.