禁用datagridview中其他列的拖放

时间:2018-05-15 00:21:42

标签: vb.net datagridview

如何禁用datagridview中其他列的拖放?就像我想在第1列中禁用拖放而其余部分未禁用。怎么做到这一点?

这是拖放代码:

Private CR As Integer, CC As Integer, CV As Object
Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
    Dim ClientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
    Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(ClientPoint.X, ClientPoint.Y)
    CR = hit.RowIndex : If CR < 0 Then Exit Sub
    CC = hit.ColumnIndex : If CC < 0 Then Exit Sub
    DataGridView1.Item(CC, CR).Value = CV
End Sub
Private Sub DataGridView1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver
    e.Effect = DragDropEffects.Move
End Sub
Private Sub DataGridView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
    Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(e.X, e.Y)
    CR = hit.RowIndex : If CR < 0 Then Exit Sub
    CC = hit.ColumnIndex : If CC < 0 Then Exit Sub
    CV = DataGridView1.Item(CC, CR).Value : If CV Is Nothing Then Exit Sub
    DataGridView1.DoDragDrop(CV, DragDropEffects.Move)
End Sub

1 个答案:

答案 0 :(得分:1)

你已经拥有了所需的一切,以便做你想做的事情,事实上你已经差不多完成它了。

命中测试信息包含您需要的所有信息。只需修改代码以检查ColumnIndex并相应地更改光标(效果):

Private Sub DataGridView1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver
    Dim ClientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
    Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(ClientPoint.X, ClientPoint.Y)

    If hit.ColumnIndex <= 0 Then
        'If we're at the first column (or no column) display a "stop" cursor.
        e.Effect = DragDropEffects.None
    Else
        'For all other columns display a "move" cursor.
        e.Effect = DragDropEffects.Move
    End If
End Sub

然后,在两个您的DragDrop事件处理程序和MouseDown事件处理程序中,更改此内容:

CC = hit.ColumnIndex : If CC < 0 Then Exit Sub

到此:

CC = hit.ColumnIndex : If CC <= 0 Then Exit Sub

如果列索引为零,则表示我们在第一列上,因此退出方法,因为我们不希望能够拖放它/从中删除项目。