Drag-and-Drop Operation in Windows Forms and C#


In windows application for performing drag and drop operation we need to understand working of DragEnter, DragDrop, MouseDown  and Dragleave events. With the help of these events we can perform drag and drop functionality very easily.


There are two steps first is dragging and second is dropping.


For better understanding we can take an example:


In this example there are two list box on window from names with ListBoxA and ListBoxB , ListBoxA contains  some city's name New York, New Delhi, Bombay, London, Paris, Berlin etc..

 

Step3.JPG


Now we have to drag item from ListBoxA and Drop to ListBoxB


We can divide all task in two steps


Step 1:  Perform Drag Operation


First the MouseDown event is used to start the drag operation.
 
In the MouseDown event for the control where the drag will begin, use the DoDragDrop method to set the data to be dragged and the allowed effect dragging will have.

 

private void listBoxA_MouseDown(object sender, MouseEventArgs e)

{

    listBoxA.DoDragDrop(listBoxA.SelectedItem, DragDropEffects.Copy)

}

 

Step 2:  Perform Drop Operation

  1. Set the AllowDrop property of ListBoxB  to true.

  2. In the DragEnter event for the ListBoxB  where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case of Listbox- Text). The code then sets the effect that will happen when the drop occurs to a value in the DragDroeffects enumeration that has these option:

    All
    Copy
    Link
    Move
    Scroll

    private
    void listBoxB_DragEnter(object sender, DragEventArgs e)
    {
        
    if (e.Data.GetDataPresent(DataFormats.Text))
            e.Effect =
    DragDropEffects.Copy;
        
    else
            e.Effect = DragDropEffects.None;


  3. In the DragDrop event for the control where the drop will occur, use the GetData method to retrieve the data being dragged.

    private
    void listBoxB_DragDrop(object sender, DragEventArgs e)
    {
        listBox2.Items.Add(e.Data.GetData(
    DataFormats.Text).ToString());
    }