在我的应用程序中,我使用代码 dgvCases.ClearSelection()
取消选择所有行。现在,视觉上没有选择任何内容,但实际上选择了第一行。这是我的代码,用于从所选行的“id”列中获取值。
Try
caseId = dgvCases.Item("Id", dgvCases.CurrentRow.Index).Value
MsgBox(caseId)
Catch ex As Exception
MsgBox("Please select a row", MsgBoxStyle.Information)
End Try
它从第一行获取不需要的“id”。那么出了什么问题,我怎样才能真正清除第一行的选择。
最佳答案
摘自 DataGridView.ClearSelection
上的 MSDN 文档,强调我的:
Clears the current selection by unselecting all selected cells.
“现在视觉上没有选择任何内容”,因为确实没有选择任何内容。您可能正在使用 CurrentRow.Index
从所选行中获取值。但是CurrentRow
和 CurrentCell
不等于 Selected
的行/单元格。这是common misconception .
来自上述链接答案的评论部分:
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 MarlinAnd 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
最好的选择是更换
caseId = dgvCases.Item("Id", dgvCases.CurrentRow.Index).Value
与
caseId = dgvCases.Item("Id", dgvCases.SelectedRows(0).Index).Value
清除您的选择后,这将触发您的 catch block 。旁注:Use if/else instead of try/catch验证是否有任何选定的行。
关于vb.net - DataGridView.ClearSelection() 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45326183/