如何在同一个datagridview中拖放行 [英] How to drag and drop row within the same datagridview

查看:156
本文介绍了如何在同一个datagridview中拖放行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows应用程序(Visual Studio)(VB)中,如何将单个行拖放到另一个帖子以允许用户重新排列该行?我还没有找到任何值得的例子。

In a Windows App (Visual Studio)(VB) how do you drag and drop a single row to another postition to allow for the user to re-order the row? I haven't found any worthy examples for this yet.

推荐答案

这是一个来自这个C#的vb版本的答案:如何将DataGridView行拖放到对方?

Here is a vb version from this C# answer: How could I Drag and Drop DataGridView Rows under each other?

表单类变量:

Private fromIndex As Integer
Private dragIndex As Integer
Private dragRect As Rectangle

拖动事件:

Private Sub DataGridView1_DragDrop(ByVal sender As Object, _
                                   ByVal e As DragEventArgs) _
                                   Handles DataGridView1.DragDrop
  Dim p As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
  dragIndex = DataGridView1.HitTest(p.X, p.Y).RowIndex
  If (e.Effect = DragDropEffects.Move) Then
    Dim dragRow As DataGridViewRow = e.Data.GetData(GetType(DataGridViewRow))
    DataGridView1.Rows.RemoveAt(fromIndex)
    DataGridView1.Rows.Insert(dragIndex, dragRow)
  End If
End Sub

Private Sub DataGridView1_DragOver(ByVal sender As Object, _
                                   ByVal e As DragEventArgs) _
                                   Handles DataGridView1.DragOver
  e.Effect = DragDropEffects.Move
End Sub

鼠标事件:

Private Sub DataGridView1_MouseDown(ByVal sender As Object, _
                                    ByVal e As MouseEventArgs) _
                                    Handles DataGridView1.MouseDown
  fromIndex = DataGridView1.HitTest(e.X, e.Y).RowIndex
  If fromIndex > -1 Then
    Dim dragSize As Size = SystemInformation.DragSize
    dragRect = New Rectangle(New Point(e.X - (dragSize.Width / 2), _
                                       e.Y - (dragSize.Height / 2)), _
                             dragSize)
  Else
    dragRect = Rectangle.Empty
  End If
End Sub

Private Sub DataGridView1_MouseMove(ByVal sender As Object, _
                                    ByVal e As MouseEventArgs) _
                                    Handles DataGridView1.MouseMove
  If (e.Button And MouseButtons.Left) = MouseButtons.Left Then
    If (dragRect <> Rectangle.Empty _
    AndAlso Not dragRect.Contains(e.X, e.Y)) Then
      DataGridView1.DoDragDrop(DataGridView1.Rows(fromIndex), _
                               DragDropEffects.Move)
    End If
  End If
End Sub

确保你有网格 AllowDrop 属性设置为true 。

Make sure you have the grids AllowDrop property set to true.

这篇关于如何在同一个datagridview中拖放行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆