2

In my application i used the code dgvCases.ClearSelection() to deselect all rows. Now visually nothing is selected but actually first row is selected. Here is my code to get value from "id" column of selected row.

Try
     caseId = dgvCases.Item("Id", dgvCases.CurrentRow.Index).Value
     MsgBox(caseId)
Catch ex As Exception
     MsgBox("Please select a row", MsgBoxStyle.Information)
End Try

it is getting "id" from first row which is not wanted. So what is going wrong and how can i actually clearSelection even from first row.

boop_the_snoot
  • 3,209
  • 4
  • 33
  • 44
Muhammad Haroon
  • 274
  • 1
  • 6
  • 20
  • in default your `caseid` is 0? so instead of `try catch` you can use `if else statement` and also `caseid` can have a value if user click on the datagrid so add an event like `cellclick` then if user click on your `datagrid` assign the value to your `caseid` i think it will solve your problem – Muj Jul 28 '17 at 05:31

1 Answers1

3

From the MSDN Documentation on DataGridView.ClearSelection, emphasis mine:

Clears the current selection by unselecting all selected cells.

"Now visually nothing is selected" because nothing is indeed selected. You are using the CurrentRow.Index to presumably get a value from the selected row. But CurrentRow and CurrentCell do not equate to a row/cell being Selected. This is a common misconception.

From the comments section of the above linked answer:

CurrentCell returns the "active" cell, which is different from "Selected". Even if there are multiple rows selected, the active cell might be somewhere else, and there can be only one active cell – Luke Marlin

And also, even if you de-select everything in the data grid view, one of the cells will still be active, so you can't rely on this being null or something like that for there being no rows selected. – Daniel Gray

Your best bet is to replace

caseId = dgvCases.Item("Id", dgvCases.CurrentRow.Index).Value

with

caseId = dgvCases.Item("Id", dgvCases.SelectedRows(0).Index).Value

After clearing your selection, this would trigger your catch block. Side note: Use if/else instead of try/catch to verify there are any selected rows.

OhBeWise
  • 5,350
  • 3
  • 32
  • 60