Home > DeveloperSection > Articles > Working with DataGridView in VC#

Working with DataGridView in VC#


C# C# 
Ratings:
1 Comment(s)
 7900  View(s)
Rate this:

Working with DataGridView in VC#

Here in this article I will show you that how to perform certain operation such as Inert and Delete in datagridview. For completing this article I had used VisualStudio 2008 and SQL Server 2008 on windows7 64 bit platform.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

 

namespace WindowsFormsApplication3

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        /// <summary>

        /// Create 3 variables which have a name da of type SqlDataAdapter class

        /// which used to execute SelectCommand, ds of type DataSet class which

        /// store all the tables of select command and _rowIndex of type int which

        /// store rowindex of datagrid view when rows or cells of gridview is

        /// clicked.

        /// </summary>

        SqlDataAdapter da;

        DataSet ds;

        int _rowIndex;

 

        /// <summary>

        /// At the load event of form establish connection with sqlserver and fetch

        /// records in dataset and then bind records of that dataset to datagridview

        /// as below I had done. Then close the connection.

        /// </summary>

        private void Form1_Load(object sender, EventArgs e)

        {

            SqlConnection con = new SqlConnection();         //Creating object of SqlConnection class.

            con.ConnectionString = "Data Source=aaa;User Id=bbb; Password =ccc;Initial Catalog=Workbook";  //Passing connection string to sqlconnection class object.

            con.Open();   //Opening connection.

            da = new SqlDataAdapter("select * from Student", con);  //Passing select query to SqlDataAdapter object.

            ds = new DataSet();   //Creating a dataset object.

            da.Fill(ds);   //Filling record in dataset by calling Fill() method of SqlDataAdapter class.

            dataGridView1.DataSource = ds.Tables[0];  //Binding records of a dataset in datagrid view.

            con.Close();  //Closing connection with sqlserver.

        }

 

        /// <summary>

        /// At the click event of cell retrive row index of the clickable

        /// cell and store it in _rowIndex variable. Then finnaly display

        /// value of that row in the textbox as I doing it in below code.

        /// </summary>

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

        {

            _rowIndex = e.RowIndex;   //Retriving row index on which cell is clicked.

            if (_rowIndex == -1)   //if _rowIndex is -1 then break the execution.

                return;

            DataGridViewRow rowData = dataGridView1.Rows[_rowIndex]; //Creating DataGridViewRow object of particlular index.

            //Displaying values of rowData object in textbox.

            textBox1.Text = rowData.Cells[0].Value.ToString();

            textBox2.Text = rowData.Cells[1].Value.ToString();

            textBox3.Text = rowData.Cells[2].Value.ToString();

            textBox4.Text = rowData.Cells[3].Value.ToString();

        }

 

        /// <summary>

        /// In this method I had written code to clear data of

        /// textbox control and making textbox control editable

        /// by setting ReadOnly property of textbox control to

        /// true and enabling Update In DataGridView button.

        /// </summary>

        private void insert_Click(object sender, EventArgs e)

        {

            TextBox[] tempTextBox = { textBox1, textBox2, textBox3, textBox4 };

            foreach (TextBox temp in tempTextBox)

            {

                temp.Clear();

                temp.ReadOnly = false;

            }

            button3.Enabled = true;

        }

 

        /// <summary>

        /// In this event I had written code to delete record from datagridview.

        /// For performing this task I need _rowIndex of specified record which

        /// I get when we click on cell of datagrid view. Then by calling

        /// RemoveAt(_rowIndex) method of DataGridView.Rows we can delete that

        /// rows.

        /// </summary>

        private void delete_Click(object sender, EventArgs e)

        {

            //By this condition I can check whether datagridview have

            //records or not.

            if (dataGridView1.Rows.Count <= 0)

            {

                MessageBox.Show("There is no records in grid view.");

                return;

            }

            //Here we check that textbox have values or not.

            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text) || string.IsNullOrEmpty(textBox4.Text))

            {

                MessageBox.Show("Please click on datagrid view rows to delete.");

                return;

            }

            //If rowindex is less than 0 then break method execution.

            if (_rowIndex < 0)

                return;

            //Here I show a confirmation message for record deleting.

            if (!(MessageBox.Show("Record deleted warning.", "Are you sure want to delete the record!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes))

                return;

            //By execution of this method record is being deleted.

            dataGridView1.Rows.RemoveAt(_rowIndex);

 

            dataGridView1.Refresh();

            TextBox[] tempTextBox = { textBox1, textBox2, textBox3, textBox4 };

            foreach (TextBox temp in tempTextBox)

                temp.Clear();

        }

 

        /// <summary>

        /// At this event I insert new record in datagridview.

        /// </summary>

        private void update_Click(object sender, EventArgs e)

        {

            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text) || string.IsNullOrEmpty(textBox4.Text))

            {

                MessageBox.Show("Please fill all the fields.");

                return;

            }

            if (ds != null && ds.Tables.Count > 0)

            {

                DataRow _newRow = ds.Tables[0].NewRow();   //Create an object of DataRow by calling NewRow() method of DataTable class.

               

                //Insert values in DataRow.

                _newRow[0] = textBox1.Text;

                _newRow[1] = textBox2.Text;

                _newRow[2] = textBox3.Text;

                _newRow[3] = textBox4.Text;

               

                //Add newly created rows in table.

                ds.Tables[0].Rows.Add(_newRow);

 

                dataGridView1.Refresh();

            }

 

            //Clear all the fields of textbox control.

            TextBox[] tempTextBox = { textBox1, textBox2, textBox3, textBox4 };

            foreach (TextBox temp in tempTextBox)

            {

                temp.Clear();

                temp.ReadOnly = true;

            }

            button3.Enabled = false;

        }

    }

}

When form is loaded it display values from database

Working with DataGridView in VC#

When we click on cell of datagridview then content of that cell comes in textbox.

Working with DataGridView in VC#

When I click on Delete Record button then confirmation message will display.

Working with DataGridView in VC#

When I click on yes button then record is deleted.

Similarly you can perform rest of operation in this article.


Working with DataGridView in VC#

By James Smith on   5 years ago

Hey Awadhendra,

Good one,


Don't want to miss updates? Please click the below button!

Follow MindStick