Dave Howson
Dave Howson

Reputation: 306

Extract a DataGridView cell value to a variable, when double-clicked

In my C# DataGridView, once I double click on a row, I want the value in the "ID" columns cell to be assigned to a variable. How do I do this??

Upvotes: 1

Views: 9024

Answers (3)

Dave Howson
Dave Howson

Reputation: 306

Thank you very much @mhan0125 and everyone else. That error came up because even though my column was name ID, it was not identified by the code as ID, so I had to go to the 'Edit Column' section and rename it from idDataGridViewTextBoxColumn to ID. Thank you once again..

Upvotes: 0

collab-with-tushar-raj
collab-with-tushar-raj

Reputation: 1287

I am not sure , Try this :-

 private void datagridview1_SelectionChanged(object sender, EventArgs e)
 {
     if (datagridview1.SelectedCells.Count > 0)
     {
         int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;

         DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];  

         string value= selectedRow.Cells["ID"].Value.ToString();


     }

I agree this is not the best approach .

Upvotes: 0

mhan0125
mhan0125

Reputation: 654

DataGridView doesn't have row double click event. But you can try cell double click event instead as following:

    private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        string value = "";
        value = dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString();
    }

Also please note to check if the e.RowIndex > -1, just in case people click the DataGridView header, it will cause exception.

Upvotes: 6

Related Questions