当用户单击控件的空白(非行)部分时,我希望取消选择 DataGridView
控件中的所有已选择行。
我应该如何做到这一点?
当用户单击控件的空白(非行)部分时,我希望取消选择 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表单上第一个可使用Tab键选择的对象。将另一个对象设置为第一个Tab键停止点(或者完全禁用DataGridView的Tab键)会禁止选择第一行。
设置
dgv.CurrentCell = null;
在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;我遇到了同样的问题,并找到了解决方案(不完全是靠自己,但有互联网在)
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;
}
}
这是一个小技巧,你能看到哪一行被选中的唯一方法是通过第一列(不是column[0],而是那个)。当你点击另一行时,你将不再看到蓝色的选择,只有箭头指示哪一行被选中。正如你所理解的,我在我的网格视图中使用了rowSelection。
=HitTestInfo.Nowhere
,我不得不将其更改为.....If myDataGridView.HitTest(e.X, e.Y) Is myDataGridView.HitTest(e.X, e.Y) Then
...按预期工作,但不确定为什么会起作用。首先实现了 HitTest 代码。 - noraIs
运算符比较两个引用变量的类型。所以你在那里做的只是检查HitTest
属性返回与...HitTest
属性相同类型的值。这就像说If True = True
。 - Cody Gray