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.