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?
Set DataGridView.MultiSelect=false and DataGridView.SelectionMode = FullRowSelect. This will make it so the user can only select a single row at a time.
SelectedRows only returns the rows if the entire row is selected (you can turn on RowSelect on the datagridview if you want). The better option is to go with SelectedCells
private void myButton_Click(object sender, EventArgs e)
{
var cell = this.ProductsGrid.SelectedCells[0];
var row = this.ProductsGrid.Rows[cell.RowIndex];
string value = row.Cells[0].Value.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With