当用户单击控件的空白(非行)部分时,我想取消选择
DataGridView
控件中的所有选定行。要取消选择
DataGridView
中的所有行和单元格,您可以 使用 ClearSelection
方法:
myDataGridView.ClearSelection()
CurrentCell
属性设置为 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
方法,类似于上面所示的方式。为了方便起见,我还想提供一个公共 DeselectAll
方法,既调用 ClearSelection
方法,又将 CurrentCell
属性设置为 Nothing
。
(代码示例都是任意的 VB.NET,因为问题没有指定语言 - 如果这不是您的母语,抱歉。)
C#版本:
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;
}
}
我发现了为什么我的第一行被默认选择,并找到了如何默认不选择它。
默认情况下,我的 datagridview 是 Windows 窗体上带有第一个制表位的对象。首先在另一个对象上设置制表位(也许完全禁用数据网格的制表位会起作用)禁用选择第一行
设置
dgv.CurrentCell = null;
当用户单击 dgv 的空白部分时。
我遇到了同样的问题并找到了解决方案(不完全是我自己解决的,但有互联网)
Color blue = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;
foreach (DataGridViewRow r in datagridIncome.Rows)
{
if (r.Cells[5].Value.ToString().Contains("1")) {
r.DefaultCellStyle.BackColor = blue;
r.DefaultCellStyle.SelectionBackColor = blue;
r.DefaultCellStyle.SelectionForeColor = letters;
}
else {
r.DefaultCellStyle.BackColor = red;
r.DefaultCellStyle.SelectionBackColor = red;
r.DefaultCellStyle.SelectionForeColor = letters;
}
}
这是一个小技巧,您可以看到选择行的唯一方法是通过第一列(不是列 [0],而是因此的列)。当您单击另一行时,您将不再看到蓝色选择,只有箭头指示已选择哪一行。如您所知,我在 gridview 中使用 rowSelection。
在 VB.net 中使用 Sub:
Private Sub dgv_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgv.MouseUp
' deselezionare se click su vuoto
If e.Button = MouseButtons.Left Then
' Check the HitTest information for this click location
If Equals(dgv.HitTest(e.X, e.Y), DataGridView.HitTestInfo.Nowhere) Then
dgv.ClearSelection()
dgv.CurrentCell = Nothing
End If
End If
End Sub
gridView1.ClearSelection();
gridView1.FocusedColumn = null;
使用这个希望这能适合你的情况