Understand CellDoubleClick Event of DataGridView Control in C#

Introduction

Today I will explain the CellDoubleClick Event of DataGridView. So let us understand the situation. In this article the DataGridView contains some records and I need to fetch a record's value when I double-click on the record within the DataGridView control. In this situation you can use the CellDoubleClick Event of the DataGridView Control.

Use the following procedure to implement it.

Step 1

Open a Windows Forms application and insert three TextBoxes and one DataGridView control on form1.

Step 2

Write the following simple code to show the table's record in the DataGridView control in the form load event.

SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP03;Initial Catalog=pulkit;User ID=sa;Password=wintellect@123");

SqlCommandBuilder cmd;

SqlDataAdapter da;

DataSet ds;

private void Form1_Load(object sender, EventArgs e)

{

 

     con.Open();

     da = new SqlDataAdapter("select *from emp5", con);

     cmd = new SqlCommandBuilder(da);

     ds = new DataSet();

     da.Fill(ds);

     dataGridView1.DataSource = ds.Tables[0];

     con.Close();

}

 

Step 3

Now you see your DataGridView control filled with the record.

datagridview-with-record.jpg

Step 4

Here I want to retrieve the value of a record when it is double-clicked in the DataGridView. To do that use the following simple code for the CellDoubleClick Event of DataGridView.

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)

{

     if (e.RowIndex > -1 && e.ColumnIndex > -1)

     {

         textBox1.Visible = textBox2.Visible = textBox3.Visible = true;

         textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();

         textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

         textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();

     }

}

 

Step 5

Now when you double-click on any DataGridView cell, all the related record values are shown in the TextBox control.

double-click-event.jpg