Drag and Drop between Controls

The control from which we drag the item is called as a drag-drop source ,for exsample a listbox.And similarly the control where we'll finally drop the dragged item is called the drag-drop target,for example a treeview control.First we need to add a mouse event handler for the listbox control.Then we should figure out that which item is directly under the mouse,when it is clicked.For that purpose,Indexfrompoint function could be a good solution.
Once we hava the text that is to be draged.we can call the DoDragDrop function.This function take two parameters.

public DragDropEffects DoDragDrop(object  data,
    DragDropEffects allowedEffects);

The first parameter is the item that we will drag out from the drag-drop source and the second one is DragDropEffects enumeration which are All,Copy,Move,Link,None,Scroll.You can make your own decision according to the demand.

private void  listBox_MouseDown(
    
object
 sender, System.Windows.Forms.MouseEventArgs e)
...

Now we have setup the drag-drop source,and we need to work on the drag-drop target,the treeview.There are four events associated with a drag-drop target.The events are DragEnter, DragOver, DragDrop and DragLeave.A DragEnter occurs when the mouse pointer has dragged something into the control's client area.A DragLeave occurs if it is dragged out of the control's client area without dropping the item.The DragOver event occurs after the DragEnter event and we need to signal our readiness to accept the dropped item.We do this by setting the Effect property of the DragEventsArg object passed to the handler to one of the DragDropEffects enumerations.(The DragDropEffects here must be the same with the DragDropEffects in the listbox_mousedown handler).

private void  treeView_DragOver(
    
object
 sender, System.Windows.Forms.DragEventArgs e)
{
    e.Effect
=
DragDropEffects.All;
}


The DragDrop event occurs if the mouse is released on top of our control's client area.We are passing a DragEventArgs object as our second parameter.This has a IDataObject member called DATA.So we call the GetDataPresent member function to to verify if the data format in the data is what we are expecting
Then once we are sure the data is in the expected format we call GetData to retrieve our string and add it to our list box.

private void  treeView_DragDrop(
    
object
 sender, System.Windows.Forms.DragEventArgs e)
{
    
if
(e.Data.GetDataPresent(DataFormats.StringFormat))
    

        
string str= (string
)e.Data.GetData(
            DataFormats.StringFormat);
            
        listBox2.Items.Add(str); 
    }

}

At last, make sure the DragOver and the DragDrop event appera at the same time.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值