C #: select row from DataGridView

I have a form with a DataGridView (of 3 columns) and Button. Every time the user clicks on the button, I want to get the values ​​stored in the first column of this 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, this.ProductsGrid.SelectedRows.Count is 0. Also, how can I guarantee that the user selects only one row and not several rows? Does this code look right?

+6
c # winforms datagridview
source share
6 answers

Set DataGridView.MultiSelect = false and DataGridView.SelectionMode = FullRowSelect. This will make it possible for the user to select only one row at a time.

+23
source share

SelectedRows returns rows only if the entire row is selected (you can include RowSelect in the datagridview if you want). The best 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(); } 
+1
source share

Well, you don’t need to iterate over all the lines in your grid, or access the SelectedRows collection. If you skip the iteration and use the SelectedRows collection, your problem is probably the wrong SelectionMode:

The SelectionMode property must be set to FullRowSelect or RowHeaderSelect for the SelectedRows property filled with selected rows.

(from MSDN )

+1
source share

You can reference a grid like an array:

 ProductsGrid[ProductsGrid.SelectedColumns[0].Index, ProductsGrid.SelectedRows[0].Index].Value; 

Selecting indexes from the first index of SelectedRowsCollection and SelectedColumnsCollection, you will get the first value if multiple rows are selected.


You can block the user from selecting only one row by setting the MultiSelect property in the DataGridView. Alternatively, you make the CellClick event:

 ProductsGrid.ClearSelection(); ProductsGrid.Rows[e.RowIndex].Selected = true; 
+1
source share

SelectedRows.Count returns the number of all selected rows. You probably want to use SelectedCells.Count .

0
source share

you can also use .BoundItem

0
source share

All Articles