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

Tin*_*ren 55 .net datagridview winforms

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

Cod*_*ray 112

要取消选择a中的所有行和单元格DataGridView,可以使用以下ClearSelection方法:

myDataGridView.ClearSelection()
Run Code Online (Sandbox Code Playgroud)

如果您不希望第一行/单元格显示为选中状态,则可以CurrentCell属性设置为Nothing/null,这将暂时隐藏焦点矩形,直到控件再次获得焦点:

myDataGridView.CurrentCell = Nothing
Run Code Online (Sandbox Code Playgroud)

要确定用户何时单击了空白部分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
Run Code Online (Sandbox Code Playgroud)

当然,您也可以将现有DataGridView控件子类化,以将所有这些功能组合到一个自定义控件中.您需要覆盖与上面显示的OnMouseUp方法类似的方法.我还想提供一个DeselectAll方便的公共方法,它既调用ClearSelection方法又将CurrentCell属性设置为Nothing.

(代码示例在VB.NET中都是任意的,因为如果这不是您的本地方言,问题没有指定语言道歉.)

  • @TaW 如果您指定了“过早”的含义,那么该评论会更有帮助。 (2认同)
  • 好吧,我发现例如在__is__构造函数中填充DGV之后“太早了”。将ClearSelection移至Form_Shown可以正常工作。也许像“布局后”?我添加了注释,因为在类似的帖子上有很多评论,发现ClearSelection对他们不起作用。因此,将其添加到投票率很高的答案似乎是一个好主意。 (2认同)

Tin*_*ren 6

谢谢Cody继承了c#的ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }
Run Code Online (Sandbox Code Playgroud)