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"};

            row = new string[] { "2", "Megha", "Verma", "B.Com" };

            row = new string[] { "3", "Disha", "Mukherjee", "B.Tech" };

            row = new string[] { "4", "Ami", "Collins", "MBA" };

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


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



One thought on “DataGridView Control in Windows Forms

  1. Pingback: Back Button Functionality in Windows Forms using C# in .NET | Programming Palace

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s