一旦我在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
答案 0 :(得分:3)
如果您查看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:您是否忘记用户可以使用键盘选择单元格? ;)