C#: Select row from DataGridView
- by Bi
Hi
I have a form with a DataGridView (of 3 columns) and a Button. Every time the user clicks on a button, I want the get the values stored in the 1st column of that row.
Here is the code I have:
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in ProductsGrid.Rows)
{
if (this.ProductsGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string value = this.ProductsGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
However when I click on myButton, the this.ProductsGrid.SelectedRows.Count is 0. Also, how do I ensure that the user selects only one row and not multiple rows?
Does this code look right?