问题描述
当用户单击控件的空白(非行)部分时,我想取消选择 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
属性 到 Nothing
/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
属性设置为 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屋!
更多推荐
[db:关键词]
发布评论