Drag and drop to datagridview in vb.net
I am using two Datagridview
in my code, I am dragging content from Me.datagridview2
and dragging it to Me.datagridview1
. This process is successful. But as soon as I click on a cell other than the deleted content cell, the dropped content disappears. Here's my code
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
You have the following doubts
1. Why does the
disappearing content disappear?
2.whenever we start editing the datagridview, the row is automatically added below. Why isn't it being added when I delete content in the datagridview.?
Please help me.
source to share
Actually, I just got an alternative to my own question. Here it is.
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
Instead of copying the content from r
row to Me.DataGridview.
all cells, I am directly adding the row r
to my named data source dragsaldet
. And it helped me.
source to share