DataGridView Control in Windows Forms

I think all of you must have used the DataGridView Control to display tabular data from a Database Table

But Let’s try a Few different things today

  • Add Columns to a DataGridView programmatically
  • Add Rows of Data
  • Select Data when the User clicks on a Particular Row.

Create a New Windows Forms Application in Visual Studio.

A Form called Form1.cs should already be there. Rename it to something meaningful. We call it DataGridView_Demo.cs.

From the Toolbox, add a DataGridView Control on the Form.

Make a Form like this.

We have added a DataGridView Control and four Label controls on top of that.

The Label controls are used to display the row data selected by the user on double clicking a row.

DataGridView Control_Design_View

To dynamically add columns and rows to the DataGridView, write the code as below in Form Load event.


 private void DataGridView_Demo_Load(object sender, EventArgs e)
        {
            dataGridView1.ColumnCount = 4;

            dataGridView1.Columns[0].Name = "Student Id";
            dataGridView1.Columns[1].Name = "First Name";
            dataGridView1.Columns[2].Name = "Last Name";
            dataGridView1.Columns[3].Name = "Course";

            string[] row = {"1", "Ankita", "Sharma", "BCA"};
            dataGridView1.Rows.Add(row);

            row = new string[] { "2", "Megha", "Verma", "B.Com" };
            dataGridView1.Rows.Add(row);

            row = new string[] { "3", "Disha", "Mukherjee", "B.Tech" };
            dataGridView1.Rows.Add(row);

            row = new string[] { "4", "Ami", "Collins", "MBA" };
            dataGridView1.Rows.Add(row);
        }

Run the project now
The o/p should look like this.

DataGridView_Running

For selecting the data of a particular row, change the SelectionMode property of the DataGridView Control to FullRowSelect
Now in the properties window, click on the Events i.e the Lightning icon.
Click on the even called CellDoubleClick.

The event should get generated on your Code Window.
Write the code as below. Here we are displaying the cell contents of a particular row in the Labels.

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            labelId.Text = dataGridView1.SelectedCells[0].Value.ToString();

            labelFName.Text = dataGridView1.SelectedCells[1].Value.ToString();

            labelLName.Text = dataGridView1.SelectedCells[2].Value.ToString();

            labelCourse.Text = dataGridView1.SelectedCells[3].Value.ToString();

        }

Snapshot of the o/p

DataGridView_SelectedRowData