Click here to Skip to main content
11,438,007 members (48,625 online)
Click here to Skip to main content

Drag and Drop between list boxes - Beginner's Tutorial

, 13 May 2002 CPOL
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)

Share

About the Author

Nish Nishant

United States United States
Nish Nishant is a Software Architect/Consultant based out of Columbus, Ohio. He has over 15 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish is a recipient of the annual Microsoft Visual C++ MVP Award since 2002 (13 consecutive awards as of 2014).

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored
C++/CLI in Action for Manning Publications in 2005, and had previously 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 vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : You can reach Nish on his google email id voidnish.

Website and Blog

Comments and Discussions

 
QuestionGood stuff, thanks Pin
victorbos20-Sep-13 9:14
membervictorbos20-Sep-13 9:14 
GeneralMy vote of 5 Pin
csmajor2717-Jan-13 7:29
membercsmajor2717-Jan-13 7:29 
GeneralMy vote of 5 Pin
SalouaK24-Sep-12 1:05
memberSalouaK24-Sep-12 1:05 
I really liked your Tutorial,I Couldn't stop laughing while reading it! Keep the good work ^^
Questiondrag and drop with multiple items Pin
Prashant26825-Jul-12 4:14
memberPrashant26825-Jul-12 4:14 
GeneralRe: drag and drop with multiple items Pin
Bong Thom13-Jul-12 17:42
memberBong Thom13-Jul-12 17:42 
GeneralMy vote of 4 Pin
sivasu_bra28-Apr-12 12:03
membersivasu_bra28-Apr-12 12:03 
Questionfix problem Pin
sanaz13x12-Aug-11 4:12
membersanaz13x12-Aug-11 4:12 
AnswerRe: fix problem Pin
jjanvier31-Aug-12 20:39
memberjjanvier31-Aug-12 20:39 
QuestionTry this Pin
Nick Alexeev20-Jun-11 9:56
memberNick Alexeev20-Jun-11 9:56 
GeneralMy vote of 5 Pin
Baesky25-Nov-10 19:11
memberBaesky25-Nov-10 19:11 
Generalquestion Pin
tintincute12-May-09 6:09
membertintincute12-May-09 6:09 
GeneralRe: question Pin
Member 33524189-Dec-09 1:25
memberMember 33524189-Dec-09 1:25 
Questionand woth datasources? Pin
piercy16-Aug-07 7:03
memberpiercy16-Aug-07 7:03 
GeneralOnly a comment Pin
oldnavy4-Aug-07 12:34
memberoldnavy4-Aug-07 12:34 
Generalvc++.net 2003- drag from explorer and drop on pic box Pin
minad_7865-Apr-07 3:53
memberminad_7865-Apr-07 3:53 
GeneralThanks and a warning! Pin
DJ Parker15-Aug-06 5:45
memberDJ Parker15-Aug-06 5:45 
GeneralDrop Outside of Application Pin
yofnik19-Nov-04 12:19
memberyofnik19-Nov-04 12:19 
Generalcombining dragging and double click Pin
baglin11-Sep-04 21:51
sussbaglin11-Sep-04 21:51 
GeneralRe: combining dragging and double click Pin
Wilson Guerra24-Sep-04 6:34
sussWilson Guerra24-Sep-04 6:34 
GeneralRe: combining dragging and double click Pin
t-timmy7-Aug-07 7:42
membert-timmy7-Aug-07 7:42 
GeneralExactly Pin
jabailo2-Sep-04 12:42
memberjabailo2-Sep-04 12:42 
GeneralOne ListView Pin
apenmann11116-Mar-04 2:29
memberapenmann11116-Mar-04 2:29 
Generala little error Pin
ldentelli5-Aug-03 4:01
memberldentelli5-Aug-03 4:01 
GeneralRe: a little error Pin
Nishant S6-Aug-03 8:46
editorNishant S6-Aug-03 8:46 
Generalstraight to the point Pin
comelite4-Aug-03 3:32
membercomelite4-Aug-03 3:32 
GeneralRe: straight to the point Pin
Nishant S4-Aug-03 3:46
editorNishant S4-Aug-03 3:46 
GeneralBIG problem ;) Pin
Sameer Khan1-Apr-03 8:24
memberSameer Khan1-Apr-03 8:24 
GeneralRe: BIG problem ;) Pin
piercy16-Aug-07 7:01
memberpiercy16-Aug-07 7:01 
QuestionWhat effects more ? Pin
WillemM7-Mar-03 6:35
memberWillemM7-Mar-03 6:35 
GeneralTreeview Pin
deepaksiv24-Dec-02 6:13
memberdeepaksiv24-Dec-02 6:13 
GeneralDrag Image Pin
Rome Singh10-Oct-02 13:23
memberRome Singh10-Oct-02 13:23 
GeneralRe: Drag Image Pin
Anonymous5-Sep-03 2:50
sussAnonymous5-Sep-03 2:50 
GeneralI Really enjoy your Article Pin
Franklin25-Sep-02 1:56
sussFranklin25-Sep-02 1:56 
GeneralRe: I Really enjoy your Article Pin
Nishant S25-Sep-02 1:58
editorNishant S25-Sep-02 1:58 
GeneralRe: I Really enjoy your Article Pin
Franklin25-Sep-02 4:01
sussFranklin25-Sep-02 4:01 
GeneralRe: I Really enjoy your Article Pin
Zaharang10-Oct-02 1:54
memberZaharang10-Oct-02 1:54 
QuestionHow to do it in MFC Pin
Pathi Gorantla23-Jul-02 21:02
memberPathi Gorantla23-Jul-02 21:02 
GeneralGood :-) Pin
Anonymous25-Mar-02 14:19
memberAnonymous25-Mar-02 14:19 
GeneralRe: Good :-) [modified] Pin
Nish [BusterBoy]25-Mar-02 14:49
memberNish [BusterBoy]25-Mar-02 14:49 
GeneralRe: Good :-) Pin
Jörgen Sigvardsson26-Mar-02 2:23
memberJörgen Sigvardsson26-Mar-02 2:23 
GeneralRe: Good :-) Pin
Nish [BusterBoy]26-Mar-02 15:41
memberNish [BusterBoy]26-Mar-02 15:41 
GeneralRe: Good :-) Pin
Sebicu20-Oct-06 0:47
memberSebicu20-Oct-06 0:47 
GeneralRe: Good :-) Pin
Nish [BusterBoy]25-Mar-02 14:50
memberNish [BusterBoy]25-Mar-02 14:50 
GeneralRe: Good :-) Pin
Anonymous6-Nov-03 6:09
sussAnonymous6-Nov-03 6:09 
GeneralRe: Good :-) Pin
Anonymous6-Nov-03 6:12
sussAnonymous6-Nov-03 6:12 
GeneralRe: Good :-) Pin
Estherino4-Nov-11 16:47
memberEstherino4-Nov-11 16:47 
GeneralRe: Good :-) Pin
Nishant Sivakumar6-Nov-11 4:36
mvpNishant Sivakumar6-Nov-11 4:36 
GeneralNish... Pin
Mazdak25-Mar-02 3:45
memberMazdak25-Mar-02 3:45 
GeneralRe: Nish... Pin
Nish [BusterBoy]25-Mar-02 8:55
memberNish [BusterBoy]25-Mar-02 8:55 
GeneralMinor suggestion Pin
James T. Johnson24-Mar-02 9:45
memberJames T. Johnson24-Mar-02 9: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 | Terms of Use | Mobile
Web04 | 2.8.150506.1 | Last Updated 14 May 2002
Article Copyright 2002 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid