如何取消选中DataGridView控件中的所有行? [英] How to deselect all selected rows in a DataGridView control?
问题描述
当用户点击控件的空白(非行)部分时,我想取消选择 DataGridView
控件中的所有选定行。
我该怎么做?
I'd like to deselect all selected rows in a DataGridView
control when the user clicks on a blank (non-row) part of the control.
How can I do this?
推荐答案
要取消选择 DataGridView
,您可以使用 ClearSelection
方法 :
To deselect all rows and cells in a DataGridView
, you can use the ClearSelection
method:
myDataGridView.ClearSelection()
如果您不想让第一行/单元格显示选择,您可以设置 CurrentCell
属性到没有
/ null
,这将暂时隐藏焦点矩形直到控件再次收到焦点:
If you don't want even the first row/cell to appear selected, you can set the CurrentCell
property to Nothing
/null
, which will temporarily hide the focus rectangle until the control receives focus again:
myDataGridView.CurrentCell = Nothing
要确定用户何时点击了 DataGridView
的空白部分,您将不得不处理其 MouseUp
事件。在这种情况下,您可以 HitTest
点击位置,并观看此表示 HitTestInfo.Nowhere
。例如:
To determine when the user has clicked on a blank part of the DataGridView
, you're going to have to handle its MouseUp
event. In that event, you can HitTest
the click location and watch for this to indicate HitTestInfo.Nowhere
. For example:
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
方法与上述方式类似。我也想提供一个公开的 DeselectAll
方法,以便方便地调用 ClearSelection
方法并设置 CurrentCell
property to Nothing
。
Of course, you could also subclass the existing DataGridView
control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp
method similar to the way shown above. I also like to provide a public DeselectAll
method for convenience that both calls the ClearSelection
method and sets the CurrentCell
property to Nothing
.
(代码示例都是任意的在VB .NET,因为这个问题没有指定一个语言 - 如果这不是你的本地方言,那就是道歉。)
(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)
这篇关于如何取消选中DataGridView控件中的所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!