当用户单击控件的空白(非行)部分时,我想取消选择 DataGridView
控件中的所有选定行。
我怎样才能做到这一点?
最佳答案
要取消选择 DataGridView
中的所有行和单元格,您可以使用 ClearSelection
method :
myDataGridView.ClearSelection()
如果您甚至不希望第一行/单元格显示为选中状态,则可以设置 CurrentCell
property到 Nothing
/null
,这将暂时隐藏焦点矩形,直到控件再次获得焦点:
myDataGridView.CurrentCell = Nothing
要确定用户何时单击了 DataGridView
的空白部分,您必须处理其 MouseUp
事件。在这种情况下,您可以HitTest
单击位置并注意它是否指示 HitTestInfo.Nowhere
。例如:
Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
''# See if the left mouse button was clicked
If e.Button = MouseButtons.Left Then
''# Check the HitTest information for this click location
If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
myDataGridView.ClearSelection()
myDataGridView.CurrentCell = Nothing
End If
End If
End Sub
当然,您还可以对现有 DataGridView
控件进行子类化,以将所有这些功能合并到一个自定义控件中。您需要覆盖其 OnMouseUp
method与上面所示的方式类似。为了方便起见,我还想提供一个公共(public) DeselectAll
方法,该方法既调用 ClearSelection
方法并将 CurrentCell
属性设置为 Nothing
.
(代码示例都是任意的 VB.NET,因为问题没有指定语言 - 如果这不是您的母语,抱歉。)
关于.net - 如何取消选择 DataGridView 控件中的所有选定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4314673/