Click here to Skip to main content
Click here to Skip to main content

Drag and Drop between list boxes - Beginner's Tutorial

, 13 May 2002
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

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.

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.
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.

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.

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)

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
QuestionGood stuff, thanks Pinmembervictorbos20-Sep-13 8:14 
GeneralMy vote of 5 Pinmembercsmajor2717-Jan-13 6:29 
GeneralMy vote of 5 PinmemberSalouaK24-Sep-12 0:05 
Questiondrag and drop with multiple items PinmemberPrashant26825-Jul-12 3:14 
GeneralRe: drag and drop with multiple items PinmemberBong Thom13-Jul-12 16:42 
Excuse me . Hello ! MY name KHRON SAMEDY now i study at RUPP(Royal University of Phnom Penh ) I have some problems how to use Array about drag items from LisBox1 to ListBox2. Pleas tell me also. From Questioner . Cry | :((
GeneralMy vote of 4 Pinmembersivasu_bra28-Apr-12 11:03 
Questionfix problem Pinmembersanaz13x12-Aug-11 3:12 
AnswerRe: fix problem Pinmemberjjanvier31-Aug-12 19:39 
QuestionTry this PinmemberNick Alexeev20-Jun-11 8:56 
GeneralMy vote of 5 PinmemberBaesky25-Nov-10 18:11 
Generalquestion Pinmembertintincute12-May-09 5:09 
GeneralRe: question PinmemberMember 33524189-Dec-09 0:25 
Questionand woth datasources? Pinmemberpiercy16-Aug-07 6:03 
GeneralOnly a comment Pinmemberoldnavy4-Aug-07 11:34 
Generalvc++.net 2003- drag from explorer and drop on pic box Pinmemberminad_7865-Apr-07 2:53 
GeneralThanks and a warning! PinmemberDJ Parker15-Aug-06 4:45 
GeneralDrop Outside of Application Pinmemberyofnik19-Nov-04 11:19 
Generalcombining dragging and double click Pinsussbaglin11-Sep-04 20:51 
GeneralRe: combining dragging and double click PinsussWilson Guerra24-Sep-04 5:34 
GeneralRe: combining dragging and double click Pinmembert-timmy7-Aug-07 6:42 
GeneralExactly Pinmemberjabailo2-Sep-04 11:42 
GeneralOne ListView Pinmemberapenmann11116-Mar-04 1:29 
Generala little error Pinmemberldentelli5-Aug-03 3:01 
GeneralRe: a little error PineditorNishant S6-Aug-03 7:46 
Generalstraight to the point Pinmembercomelite4-Aug-03 2:32 
GeneralRe: straight to the point PineditorNishant S4-Aug-03 2:46 
GeneralBIG problem ;) PinmemberSameer Khan1-Apr-03 7:24 
GeneralRe: BIG problem ;) Pinmemberpiercy16-Aug-07 6:01 
QuestionWhat effects more ? PinmemberWillemM7-Mar-03 5:35 
GeneralTreeview Pinmemberdeepaksiv24-Dec-02 5:13 
GeneralDrag Image PinmemberRome Singh10-Oct-02 12:23 
GeneralRe: Drag Image PinsussAnonymous5-Sep-03 1:50 
GeneralI Really enjoy your Article PinsussFranklin25-Sep-02 0:56 
GeneralRe: I Really enjoy your Article PineditorNishant S25-Sep-02 0:58 
GeneralRe: I Really enjoy your Article PinsussFranklin25-Sep-02 3:01 
GeneralRe: I Really enjoy your Article PinmemberZaharang10-Oct-02 0:54 
QuestionHow to do it in MFC PinmemberPathi Gorantla23-Jul-02 20:02 
GeneralGood :-) PinmemberAnonymous25-Mar-02 13:19 
GeneralRe: Good :-) [modified] PinmemberNish [BusterBoy]25-Mar-02 13:49 
GeneralRe: Good :-) PinmemberJörgen Sigvardsson26-Mar-02 1:23 
GeneralRe: Good :-) PinmemberNish [BusterBoy]26-Mar-02 14:41 
GeneralRe: Good :-) PinmemberSebicu19-Oct-06 23:47 
GeneralRe: Good :-) PinmemberNish [BusterBoy]25-Mar-02 13:50 
GeneralRe: Good :-) PinsussAnonymous6-Nov-03 5:09 
GeneralRe: Good :-) PinsussAnonymous6-Nov-03 5:12 
GeneralRe: Good :-) PinmemberEstherino4-Nov-11 15:47 
GeneralRe: Good :-) PinmvpNishant Sivakumar6-Nov-11 3:36 
GeneralNish... PinmemberMazdak25-Mar-02 2:45 
GeneralRe: Nish... PinmemberNish [BusterBoy]25-Mar-02 7:55 
GeneralMinor suggestion PinmemberJames T. Johnson24-Mar-02 8:45 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 14 May 2002
Article Copyright 2002 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid