拖放数据操作:从DataGridView拖放数据到ListBox中。

本文介绍了一个简单的应用程序案例,演示如何将DataGridView中的选中行通过拖放操作转移到ListBox中。该过程涉及DataGridView与ListBox的AllowDrop属性设置,以及MouseDown、DragEnter和DragDrop事件的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从DataGridView拖放选中的行到ListBox中。项目中要用到拖放操作,在网上找不到,不过研究了许多别人的代码。自己写的简单代码。

 

 

界面中要一个DataGridView1, ListBox1 ,两个Button。

代码如下:

Public   Class FrmDvDrag

    
Private Sub FrmDvDrag_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        
Me.DataGridView1.Columns.Add("code""code")
        
Me.DataGridView1.Columns.Add("name""name")
        
Me.DataGridView1.AllowDrop = True
        
Me.ListBox1.AllowDrop = True
        
Me.DataGridView1.Rows.Add("1""23423")
        
Me.DataGridView1.Rows.Add("2""asaer")
    
End Sub


    
Private Sub DataGridView1_MouseDown(ByVal sender As ObjectByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
        
If e.Button = Windows.Forms.MouseButtons.Left And Me.DataGridView1.SelectedRows.Count > 0 Then
            
Dim SelRow As DataGridViewSelectedRowCollection
            SelRow 
= Me.DataGridView1.SelectedRows
            
Me.DataGridView1.DoDragDrop(SelRow, DragDropEffects.Copy)
        
End If
    
End Sub


    
Private Sub ListBox1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox1.DragEnter
        
If e.Data.GetDataPresent(GetType(DataGridViewSelectedRowCollection)) Then
            e.Effect 
= DragDropEffects.Copy
        
Else
            e.Effect 
= DragDropEffects.None
        
End If
    
End Sub


    
Private Sub ListBox1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox1.DragDrop
        
If e.Data.GetDataPresent(GetType(DataGridViewSelectedRowCollection)) Then
            
Dim dr As DataGridViewSelectedRowCollection
            dr 
= e.Data.GetData(GetType(DataGridViewSelectedRowCollection))
            
For i As Integer = 0 To dr.Count - 1
                
Me.ListBox1.Items.Add(dr.Item(i).Cells(0).Value)
            
Next
        
End If
    
End Sub


    
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        
Me.ListBox1.Items.Clear()
    
End Sub


    
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        
Me.Close()
    
End Sub

End Class
 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值