2015-04-06 46 views
1

一旦我在datagridview中选择了多个单元格,我希望当前单元格等于在datagridview中选定的第一个单元格。我遇到的问题是,在选择完成后(在鼠标上),我将当前单元格设置为第一个选定单元格(me.datagridview.currentcell =),但这会删除datagridview中的所有其他选择。有没有人知道改变当前单元格的方式,而不必删除datagridview选项。下面当前示例代码:更改当前单元格,但不删除选区

Private Sub DataGridView1_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp 

    a = 0 
    Do While a < Me.DataGridView1.RowCount 
     b = 0 
     Do While b < Me.DataGridView1.ColumnCount 
      If Me.DataGridView1.Rows(a).Cells(b).Selected = True Then 
       Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(a).Cells(b) 
       GoTo skipstep 
      End If 
      b += 1 
     Loop 
     a += 1 
    Loop 

    skipstep: 

    End Sub 

回答

2

如果你看一下在CurrentCell属性,你会看到它对ClearSelection通话SetCurrentCellAddressCore之前的源代码。但是你不能称之为“SCCAC”,因为它定义为Protected。所以我最好的建议是你将DGV分类并创建一个新的公共方法。

Public Class UIDataGridView 
    Inherits DataGridView 

    Public Sub SetCurrentCell(cell As DataGridViewCell) 
     If (cell Is Nothing) Then 
      Throw New ArgumentNullException("cell") 
     'TODO: Add more validation: 
     'ElseIf (Not cell.DataGridView Is Me) Then 
     End If 
     Me.SetCurrentCellAddressCore(cell.ColumnIndex, cell.RowIndex, True, False, False) 
    End Sub 

End Class 

如果您不想继承DGV,那么反射是您唯一的选择。

Imports System.Reflection 

Private Sub HandleCellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown 
    Me.firstCell = If(((e.ColumnIndex > -1) AndAlso (e.RowIndex > -1)), Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), Nothing) 
End Sub 

Private Sub HandleCellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp 
    If ((Not Me.firstCell Is Nothing) AndAlso (Me.firstCell.Selected AndAlso (Me.DataGridView1.SelectedCells.Count > 1))) Then 

     Dim type As Type = GetType(DataGridView) 
     Dim flags As BindingFlags = (BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic) 
     Dim method As MethodInfo = type.GetMethod("SetCurrentCellAddressCore", flags) 

     method.Invoke(Me.DataGridView1, {Me.firstCell.ColumnIndex, Me.firstCell.RowIndex, True, False, False}) 

     Debug.WriteLine("First cell is current: {0}", {(Me.DataGridView1.CurrentCell Is Me.firstCell)}) 

    End If 
End Sub 

Private firstCell As DataGridViewCell 

PS:你忘了,用户可以通过使用键盘选择单元格? ;)

+0

这是一个非常好的答案,谢谢堆。不能让你的第一个选项工作(我对VB.NET来说很新,我需要更多地使用它),但是你的第二个选项就像魅力一样。再次感谢!!! – Jarron 2015-04-06 10:18:22

+0

对于选项1,这是您需要执行的操作:在“解决方案资源管理器”窗格中,右键单击您的应用程序名称并转到“添加>类”。将名称更改为“UIDataGridView.vb”,然后单击添加。将自动生成的代码替换为我答案中的代码(第一部分)。重建您的解决方案。自定义控件现在位于“工具箱”窗格的顶部。您可以将此控件拖放到表单上。哦,既然你是新手,这里有一个pro-tip:将严格的编译选项设置为“On”。这个非常重要。 https://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx?f=255&MSPPError=-2147217396 – 2015-04-06 10:29:40

相关问题