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.
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.
object sender, System.Windows.Forms.MouseEventArgs e)
... {
if(listBox1.Items.Count==0)
return;
int index = listBox1.IndexFromPoint(e.X,e.Y);
string s = listBox1.Items[index].ToString();
DragDropEffects dde1=DoDragDrop(s,
DragDropEffects.All);
if(dde1 == DragDropEffects.All )
...{
listBox1.Items.RemoveAt(listBox1.IndexFromPoint(e.X,e.Y));
}
}
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).
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.
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.