articles

Home / DeveloperSection / Articles / Insert, Update, Delete in DataGridView

Insert, Update, Delete in DataGridView

Anonymous User24256 27-Aug-2011

DataGridView is a control which is widely used in developing window application.  DataGridView is an efficient way through which we can display database table data into customizable format that is where we can edit information, delete information, insert information or update information indirectly from original database and after the user confirmation these changes reflects into the original database. DataGridView control helps to display data into customizable grid. DataGridView control provides the flexibility to show data, modify data and much more with flexible tabular format.

Here I am using a datagridview control with different functionality such as update, delete, insert and much more. Let’s see a brief description of example.

Step 1: First open visual studio and click on file menu and select new project and then click project for window application.

Step 2: After Successful creating a new project then drag datagridview control from toolbox and drop it into window form where you want to use it.

Here I making window form with design which are appears as;

Insert, Update, Delete in DataGridView

After successful design of window form write the following code to perform the action according to buttons.

publicpartialclassWelcome : Form
    {
        ///<summary>
        ///  declare the varraible to use in different mode
        ///</summary>
        boolcheck=false;
        SqlDataAdapterda;
        SqlConnectioncon;
        DataTabledt;
        intindex ;
        stringtxt_Name;
        stringtxt_Address;
        stringtxt_Designation;
        stringtxt_Department;
      
        publicWelcome()
        {
            InitializeComponent();
            /// validation error message visibility false
            label2.Visible= false;
 
            /// bind table data with data grid view
            DataBind();
            /// disable the update button at form loading time
            btn_Update.Enabled= false;
        }
 
        ///<summary>
        ///  Data bind method use to bind table data with datagrid view
        ///</summary>
        publicvoidDataBind()
        {
            /// bind database table data with datagrid view
             con=newSqlConnection(ConnectionString.connString());
             con.Open();
             da=newSqlDataAdapter();
             da.SelectCommand= newSqlCommand("Select * from tblGridView",con);
            /// create sqlcommandbuilder to update, delete etc. in data grid view
             SqlCommandBuildercmdbuilder= new SqlCommandBuilder(da);
            // data table to hold table data
             dt=newDataTable();
             da.Fill(dt);
            dataGridView1.DataSource=dt;
            /// define all column of datagrid view  readonly
             ReadOnlyGrid();
        }
 
        ///<summary>
        ///  readonlygrid method use to declare all cell of datagridview is read only
        ///</summary>
        publicvoidReadOnlyGrid()
        {
            // define all cell datagrid view readonly
            for (inti=0; i<dataGridView1.Columns.Count; i++)
            {
                dataGridView1.Columns[i].ReadOnly= true;
            }
        }
 
        ///<summary>
        /// this method use to make empty the text field
        ///</summary>
        publicvoidEmptyField()
        {
            // make empty all text field
            textBox1.Enabled= true;
            TextBox[] txtName= { textBox1, textBox2, textBox3, textBox4, textBox5 };
            for (inti=0; i<txtName.Length; i++)
            {
                txtName[i].Text=String.Empty;
            }
        }
 
        ///<summary>
        ///  validate the user to input integer value only
        ///</summary>      
        privatevoid textBox1_Validating(objectsender, CancelEventArgse)
        {
            /// validating event of textbox when user input userid value
            try
            {
                if (textBox1.Text!= "")
                {
                    intnum= Convert.ToInt32(textBox1.Text);
                    if (num>0&&num<=9999)
                    {
                        check=true;
                        label2.Text=String.Empty;
                    }
                    else { label2.Visible=true; }
                }
            }
            catch (Exceptionae)
            {
                label2.Visible=true;
            }
 
        }
        ///<summary>
        ///  After the Succesful validating user here hide error message
        ///</summary>
        privatevoid textBox1_Validated(objectsender, EventArgse)
        {
            /// check after the validating event userid validation
            if (check)
            {
                label2.Visible=false;
                label2.Text=String.Empty;
           
            }
        }
        ///<summary>
        /// this method help to insert data into  sql table
        ///</summary>
        privatevoid btn_Insert_Click(objectsender, EventArgse)
        {
            // insert new record
            try
            {
                /// check any field if empty
                if (textBox1.Text== ""||textBox2.Text==""||textBox3.Text ==""||textBox4.Text==""|| textBox5.Text=="")
                {
                    MessageBox.Show("Please fill all enteries");
                }
                    // check if validation message are showing
                elseif (label2.Text!= "")
                {
                    MessageBox.Show("Userid must be integer value");
                }
                else
                {
                    // insert new record and bind with database table
                    /// aoss the parameter in stored procedure gridviewtest
                    SqlCommandcmd= new SqlCommand("GridviewTest", con);
                    cmd.CommandType=CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Userid", textBox1.Text);
                    cmd.Parameters.AddWithValue("@Name", textBox2.Text);
                    cmd.Parameters.AddWithValue("@Address", textBox3.Text);
                    cmd.Parameters.AddWithValue("@Designation", textBox4.Text);
                    cmd.Parameters.AddWithValue("@Department", textBox5.Text);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Data Successfully inserted");
                    // bind table data with gridview
                    DataBind();
                    // make empty text field
                    EmptyField();
                }
            }
            catch (Exceptionae) { MessageBox.Show(ae.ToString().Substring(0,148)); }
          
        }
        ///<summary>
        ///  this method help to update data of existing information
        ///</summary>
        privatevoid btn_Update_Click(objectsender, EventArgse)
        {
           
            try
            {
                /// update existing information
                /// check if any textfield is empty
             
                if ((textBox2.Text== ""||textBox3.Text==""||textBox4.Text ==""||textBox5.Text==""))
                {
                    MessageBox.Show("Fill all enteries");
                }
                /// if  no modification has been changed
                elseif (txt_Name== textBox2.Text&&txt_Address==textBox3.Text &&txt_Designation==textBox4.Text&& txt_Department==textBox5.Text)
                {
 
                }
 
                else
                {
                    /// update information by calling gridviewupdate  stored procedure
                    SqlCommandcmd= new SqlCommand("GridviewUpdate", con);
                    cmd.CommandType=CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Userid", textBox1.Text);
                    cmd.Parameters.AddWithValue("@Name", textBox2.Text);
                    cmd.Parameters.AddWithValue("@Address", textBox3.Text);
                    cmd.Parameters.AddWithValue("@Designation", textBox4.Text);
                    cmd.Parameters.AddWithValue("@Department", textBox5.Text);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Data Successfully updated");
                    DataBind();
                    EmptyField();
                }
            }
            catch (Exceptionae) { MessageBox.Show(ae.ToString()); }
        }
        ///<summary>
        /// this method fill all the existing data when double click on datagridview row header to update data
        ///</summary>
      privatevoid dataGridView1_RowHeaderMouseDoubleClick(objectsender, DataGridViewCellMouseEventArgse)
        {
            /// update existing information by double click on rowheader of datagridview
            btn_Update.Enabled= true;
            btn_Delete.Enabled= false;
            btn_Insert.Enabled= false;
            textBox1.Text=dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            textBox2.Text=dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            txt_Name=textBox2.Text;
            textBox3.Text=dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
            txt_Address=textBox3.Text;
            textBox4.Text=dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
            txt_Designation=textBox4.Text;
            textBox5.Text=dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
            txt_Department=textBox5.Text;
 
            textBox1.Enabled= false;
        }
 
        ///<summary>
        ///  cancel button method to disable or enable button
        ///</summary>
        privatevoidbtn_Edit_Click(objectsender, EventArgse)
        {
            /// event when clicked on cancel button
            btn_Update.Enabled= false;
            btn_Insert.Enabled= true;
            btn_Delete.Enabled= true;
            EmptyField();
               
        }
        ///<summary>
        /// Delete existing record when clicked on dalete button either select single row or multiple row
        ///</summary>
     
        privatevoid btn_Delete_Click(objectsender, EventArgse)
        {
            // check if multiple row selected for delete
 
            if(dataGridView1.SelectedRows.Count>1)
            {  
                /// show message box with notification to delete data from table 
                stringmessageText= "Do you want to permanent delete these data";
                stringcaption= "Delete Records";
                MessageBoxButtonsbutton=MessageBoxButtons.OKCancel;
                if (MessageBox.Show(messageText, caption, button) == DialogResult.OK)
                {
                    foreach (DataGridViewRowdr indataGridView1.SelectedRows)
                    {
                        intval= Convert.ToInt32(dr.Cells["Userid"].Value.ToString());
                        SqlCommandcmd= new SqlCommand("GridViewDelete", con);
                        cmd.CommandType=CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@userid", val);
                        cmd.ExecuteNonQuery();
                    }
                    DataBind();
                }
 
            }
            else
            {
                /// if one row select for delete
                if (index>0)
                {
                   stringmessageText= "Do you want to permanent delete data";
                   stringcaption= "Delete Records";
                   MessageBoxButtonsbutton=MessageBoxButtons.OKCancel;
                 
                    /// check confirmation of user to delete data from table
 
                   if (MessageBox.Show(messageText, caption, button) == DialogResult.OK)
                   {
                       SqlCommandcmd= new SqlCommand("GridViewDelete", con);
                       cmd.CommandType=CommandType.StoredProcedure;
                       cmd.Parameters.AddWithValue("@userid", index);
                       cmd.ExecuteNonQuery();
                       DataBind();
                       index=0;
                   }
                }
                elseif(dataGridView1.Rows.Count <=0)
                {
                    // grid view have no record
                  MessageBox.Show("No data found to delete ");
                }
                else
                {
                    MessageBox.Show("Select row to delete data");
                }
 
                }
        }
        ///<summary>
        /// this method fire when singleclick on datagridview row header, it is used for delete single row
        ///</summary>
        privatevoid dataGridView1_RowHeaderMouseClick(objectsender, DataGridViewCellMouseEventArgse)
        {
            /// row select for delete data form data table
            index=Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Userid"].Value.ToString());
        }
 
        privatevoid dataGridView1_CellClick(object sender, DataGridViewCellEventArgse)
        {
            // set index value in every cell click event
            index=0;
        }
    }
  

After Write the above codes debugs the program and perform the action.

Insert, Update, Delete in DataGridView

Now insert the information

Insert, Update, Delete in DataGridView

When you click on insert button then a confirmation message box open and when you click on ok button then new record will be shown into datagridview.

Insert, Update, Delete in DataGridView

Now in the same manner you can perform all action like update, delete etc.

 


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By