Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C#
Article

Drag and Drop between list boxes - Beginner's Tutorial

Rate me:
Please Sign up or sign in to vote.
4.72/5 (82 votes)
13 May 2002CPOL6 min read 436.4K   11.4K   91   55
An introduction to drag and drop in .NET

Preamble

Yeah, you are not alone when you dream of dragging and dropping. I did dream too. It's such an infinite ecstasy when you feel the power of the mouse. Just clicking on an item, dragging it to some other window or control and to simply drop it there gives you a feeling of supremacy. Alright, I guess I better stop with this juvenile gobbledygook and start talking serious stuff. Just today morning I was thinking that it should be quite easy to drag and drop in .NET because that's what I have basically encountered whenever I tried to do something with .NET. Everything is always so much more easier than when you are doing normal SDK/MFC stuff or the Non-dot-Net stuff.

I created a simple C# Windows Forms application. Then I added two list boxes using the form designer. Now my intention was to fill up the list box on the left with some text. By the time I complete the small sample program, I should be able to drag an item from the list box on the left and to drop it on the list box on the right. It should have taken me only about an hour or so, but I was really stuck at one point and luckily for me, James T Johnson offered a word of advice and solved all my problems. He really is an amazing character, that JTJ, you would need to get really close to feel it though.

Screenshot

Well, before we proceed you can ogle at the screen shot made on *ahem* Windows XP Professional. I know most of you are thinking now that this guy seems to be crazy if he thinks using XP is a big deal. But alas, little do they know the tribulations faced by a 3rd worlder such as myself. In fact it's a bit of a good fortune that I am not still using DOS 5.0. Yeah, things are that bad.

Image 1

Let's go ahead

The control from which we drag the item is called as a drag-drop source. In our case this would be the list box on the left. And similarly the control where we'll finally drop the dragged item is called the drag-drop target, which for us would be the list box on the right. For those of you who haven't dragged and dropped before [specially people coming from a Linux background], it's quite easy to accomplish. Click on an item, now without raising your finger off the mouse button drag the mouse cursor to some other point, and release the mouse button, whereby you drop the item on that precise point. Make sure you drop it on a drag-drop target control or window, otherwise the whole exercise would be meaningless.

The first thing we need to do is to make sure that the right list box is a drop target. Controls have a property called AllowDrop which we need to set to true. You can do this using the form designer or manually via code.

C#
this.listBox2.AllowDrop = true;

Now we need to add a handler for the MouseDown event for the left list box. A MouseDown event occurs when you click the mouse anywhere within the list box control.

C#
this.listBox1.MouseDown += new MouseEventHandler(
    this.listBox1_MouseDown);

Well, the MouseDown handler is simplicity itself. First we figure out which item is directly under the mouse, when it is clicked. For this purpose we use the IndexFromPoint function which turned out to be just what I wanted. This was where James was of immense help to me. He pointed out this nice little function to me just when I was groping like a drunken cat in deep black darkness. Well I simply cannot stop singing JTJ's praises today. Pardon me folks.

Once we have the text that is to be dragged, we call the DoDragDrop function. This function takes two parameters.

C#
public DragDropEffects DoDragDrop(object data,
	DragDropEffects allowedEffects);

The first argument is the object that will be dragged out of the drag-drop source. In our case this will be the text of the item in the list box that is directly under the mouse. The second argument is a DragDropEffects enumeration. I am showing you the various values possible in the table below. Of course you can also look it up in MSDN. I am using DragDropEffects.All cause that's what we are doing. We copy the data to the target and remove it from the source. We need to check the value returned by DoDragDrop and if it is equal to DragDropEffects.All, this means that the item was safely dropped on a valid target and thus we remove the item from our list box. Otherwise we should not remove it as it means that the dropping was done in a meaningless area.

DragDropEffects Enumeration
Member Name Description
All The data is copied, removed from the drag source, and scrolled in the drop target.
Copy The data is copied to the drop target.
Link The data from the drag source is linked to the drop target.
Move The data from the drag source is moved to the drop target.
None The drop target does not accept the data.
Scroll Scrolling is about to start or is currently occurring in the drop target.
C#
private void listBox1_MouseDown(
    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)); 
    } 
}

Alright, now that we have setup the drag-drop source we need to work on the drag-drop target which for us is the listbox on the right. 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. We won't concern ourselves with those two events.

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. If we set this to DragDropEvents.None, then we have essentially rejected the drop.

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

The DragDrop event occurs if the mouse is releases on top of our control's client area. If we have not signaled our readiness to accept the drop, then instead of a DragDrop event a DragLeave event occurs. We are passed a DragEventArgs object as our second parameter. This has a IDataObject member called Data. We call the GetDataPresent member function on it to verify if the data format in the data is what we are expecting. In our case we are expecting a string. So we check with DataFormats.StringFormat. 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.

C#
private void listBox2_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); 
    }
}

That's about it I guess. This is just a minimal introduction to dragging and dropping. But you can play around with it more. Feel free to post you comments on the article forum, but do not mail me directly, specially not to my busterboy.org email address. It's not a fast server for me and I do not enjoy popping too many mails from there. Thank You.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
BugDragDropNish.exe is a trojan virus. Pin
Sumit Datta20-Nov-17 21:40
Sumit Datta20-Nov-17 21:40 
GeneralMy vote of 4 Pin
Destiny77724-May-16 9:46
Destiny77724-May-16 9:46 
GeneralRe: My vote of 4 Pin
Nish Nishant24-May-16 9:51
sitebuilderNish Nishant24-May-16 9:51 
GeneralRe: My vote of 4 Pin
Destiny77724-May-16 9:52
Destiny77724-May-16 9:52 
GeneralRe: My vote of 4 Pin
Nish Nishant24-May-16 9:55
sitebuilderNish Nishant24-May-16 9:55 
QuestionGood stuff, thanks Pin
victorbos20-Sep-13 8:14
victorbos20-Sep-13 8:14 
GeneralMy vote of 5 Pin
Taysoren17-Jan-13 6:29
Taysoren17-Jan-13 6:29 
GeneralMy vote of 5 Pin
SalouaK24-Sep-12 0:05
SalouaK24-Sep-12 0:05 
Questiondrag and drop with multiple items Pin
Prashant26825-Jul-12 3:14
Prashant26825-Jul-12 3:14 
GeneralRe: drag and drop with multiple items Pin
Bong Thom13-Jul-12 16:42
Bong Thom13-Jul-12 16:42 
GeneralMy vote of 4 Pin
sivasu_bra28-Apr-12 11:03
sivasu_bra28-Apr-12 11:03 
Questionfix problem Pin
sanaz13x12-Aug-11 3:12
sanaz13x12-Aug-11 3:12 
AnswerRe: fix problem Pin
jjanvier31-Aug-12 19:39
jjanvier31-Aug-12 19:39 
QuestionTry this Pin
Nick Alexeev20-Jun-11 8:56
professionalNick Alexeev20-Jun-11 8:56 
GeneralMy vote of 5 Pin
Baesky25-Nov-10 18:11
Baesky25-Nov-10 18:11 
Generalquestion Pin
tintincute12-May-09 5:09
tintincute12-May-09 5:09 
GeneralRe: question Pin
Member 33524189-Dec-09 0:25
Member 33524189-Dec-09 0:25 
Questionand woth datasources? Pin
piercy16-Aug-07 6:03
piercy16-Aug-07 6:03 
GeneralOnly a comment Pin
oldnavy4-Aug-07 11:34
oldnavy4-Aug-07 11:34 
Generalvc++.net 2003- drag from explorer and drop on pic box Pin
minad_7865-Apr-07 2:53
minad_7865-Apr-07 2:53 
GeneralThanks and a warning! Pin
DJ Parker15-Aug-06 4:45
DJ Parker15-Aug-06 4:45 
GeneralDrop Outside of Application Pin
yofnik19-Nov-04 11:19
yofnik19-Nov-04 11:19 
Generalcombining dragging and double click Pin
baglin11-Sep-04 20:51
baglin11-Sep-04 20:51 
GeneralRe: combining dragging and double click Pin
wguerram24-Sep-04 5:34
wguerram24-Sep-04 5:34 
GeneralRe: combining dragging and double click Pin
t-timmy7-Aug-07 6:42
t-timmy7-Aug-07 6:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.