在vb.net中的datagridview中拖放

时间:2014-11-13 20:15:32

标签: vb.net datagridview

我在代码中使用了两个Datagridview,我将Me.datagridview2中的内容拖放到Me.datagridview1上。此过程成功。但是,只要我单击除了丢弃的内容单元格以外的单元格,删除的内容就会消失。这是我的代码

 Private Sub DataGridView2_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles DataGridView2.MouseDown
    Try
        If Me.DataGridView2.SelectedRows.Count = 0 Then
            Exit Sub
        End If
        Me.DataGridView2.DoDragDrop(Me.DataGridView2.SelectedRows(0), DragDropEffects.All)
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
  Try
        Dim r As DataGridViewRow = e.Data.GetData(GetType(DataGridViewRow))
        If Me.DataGridView1.SelectedRows.Count = 0 Then
            Exit Sub
        End If

        Dim i As Integer = Me.DataGridView1.SelectedRows(0).Index
        Me.DataGridView1.Rows(i).Cells(1).Value = r.Cells(0).Value
        Me.DataGridView1.Rows(i).Cells(2).Value = r.Cells(1).Value
        Me.DataGridView1.Rows(i).Cells(3).Value = r.Cells(2).Value
        Me.DataGridView1.Rows(i).Cells(4).Value = r.Cells(3).Value

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

Private Sub DataGridView1_DragEnter(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragEnter
    Try
        e.Effect = DragDropEffects.Copy
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub



有以下疑虑
1.为什么丢弃的内容会消失。
2.每当我们开始编辑datagridview时,下面会自动添加一行。当我在datagridview中删除内容时,为什么它不会被添加。

请帮帮我。

1 个答案:

答案 0 :(得分:3)

实际上,我只是替代了自己的问题。就是这样。

  Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
  Try
        Dim r As DataGridViewRow = e.Data.GetData(GetType(DataGridViewRow))
        If Me.DataGridView1.SelectedRows.Count = 0 Then
            Exit Sub
        End If
        Dim i As Integer = Me.DataGridView1.SelectedRows(0).Index
        dragseldet.Tables(0).Rows.Add("", r.Cells(0).Value, r.Cells(1).Value, r.Cells(2).Value, r.Cells(3).Value, 0, 0)
        dragseldet.AcceptChanges()
        'Me.DataGridView1.Rows(i).Cells(1).Value = r.Cells(0).Value
        'Me.DataGridView1.Rows(i).Cells(2).Value = r.Cells(1).Value
        'Me.DataGridView1.Rows(i).Cells(3).Value = r.Cells(2).Value
        'Me.DataGridView1.Rows(i).Cells(4).Value = r.Cells(3).Value

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub


我没有将内容从r行复制到Me.DataGridview.所有单元格,而是直接将r行添加到名为dragsaldet的数据源中。这对我有用。