.net - 如何取消选择 DataGridView 控件中的所有选定行?

标签 .net winforms datagridview

当用户单击控件的空白(非行)部分时,我想取消选择 DataGridView 控件中的所有选定行。
我怎样才能做到这一点?

最佳答案

要取消选择 DataGridView 中的所有行和单元格,您可以使用 ClearSelection method :

myDataGridView.ClearSelection()

如果您甚至不希望第一行/单元格显示为选中状态,则可以设置 CurrentCell propertyNothing/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/

相关文章:

c# - 用大量数据填充 DataGridView 的最佳方法

c# - 线程中的定时器问题

.net - Rx 中的 IConnectableObservables

c# - 在 UI 上延迟调用 + 更新 CountDown

c# - 遍历对象的属性并获取 DateTime 类型属性的值

c# - WPF 应用程序 : Controls look like . NET 2.0 中的 WinForms 对话框

c# - 获取调用线程

c# - 有没有办法确定 Microsoft XPS Document Writer 在系统上是否可用且功能正常

c# - 在设计时将换行符添加到标签的文本

vb.net - 在 DataGridView 中获取 "current cell"的 X/Y 坐标?