vb.net - DataGridView.ClearSelection() 未按预期工作

标签 vb.net datagridview

在我的应用程序中,我使用代码 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 从所选行中获取值。但是CurrentRowCurrentCell不等于 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 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

最好的选择是更换

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/

相关文章:

c# - 如何根据另一行数据 GridView 汇总一行?

jquery - 无法在 ASP.NET 和 VB.NET 网站的 CSS 中找到 ColorBox

.net - 告诉 datagridview 忽略 'NULL' 单元格

vb.net - VB.NET 中的 GoTo 语句和替代方案

mysql - 使用关键字搜索数据库,将显示数据库中具有该关键字的所有主题

c# - C#中如何将数据表绑定(bind)到datagridview

c# - 按照添加顺序访问 DataGridView 行

c# - 如何对具有日期时间值但显示为字符串的 DataGridView 列进行排序?

c# - 如何提高 GDI 的 DrawImage(Unscaled) 的性能?

vb.net - FxCop 或其他实用程序需要 VB.NET 中的内联文档?