Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Select row from DataGridView

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?

like image 722
Bi. Avatar asked Apr 29 '10 22:04

Bi.


2 Answers

Set DataGridView.MultiSelect=false and DataGridView.SelectionMode = FullRowSelect. This will make it so the user can only select a single row at a time.

like image 102
Serapth Avatar answered Oct 10 '22 05:10

Serapth


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();
}
like image 27
BFree Avatar answered Oct 10 '22 06:10

BFree