Reputation: 306
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
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
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
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