Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Windows Forms C# » Drag and Drop Using C#

Drag and Drop Using C#

Drag and Drop in C# has been a question on the UseNet and many websites on C# so I have decided to tackle the problem here. This is an update of the directory tree component download on this web site.

Author Rank :
Page Views : 369748
Downloads : 5314
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DragDropDirectoryTree.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Tools Used: Visual C# .NET



Drag and Drop in C# has been a question on the UseNet and many websites on C# so I have decided to tackle the problem here. This is an update of the directory tree component download on this web site. The directory component allows you to peruse directories and files. To demonstrate drag and drop, I've added to the component the capability of dragging and dropping files from within the treeview. If you hold the control key down, you can also copy files. All the source for this is in the download above.

Drag and Drop

Microsoft has added a series of properties and events to help you use drag and drop with your controls.  You must set the AllowDrop property to allow for dragging and dropping within the tree view.  Also there are about 5 major events available for trapping drag drop operations.  We use 4 of them here:  ItemDrag, DragOver, DragEnter, and DragDrop.

Event How It is Triggered
ItemDrag The Initial Event triggered when the user starts to drag an item in the treeview.
DragOver This is specific to treeviews and listviews and traps the item being dragged in the event parameter. AlsoHere is where you call DoDragDrop 
DragEnter This event occurs when the user drags over a drag and drop control with the mouse during a drag drop operation 
DragLeave Occurs when the user moves the mouse onto the control when dragging an object. 
DragDrop Occurs when the user releases the mouse over the drop target 
GiveFeedback Gives feedback about the effects and the current cursor

The Drag and Drop functionality also has another facet of control called DragDropEffects. Below is a table of these enumerations:

Effects Description
Move The drag appears as a box along with the cursor. Data is moved to the target through the drop operation.
Copy The drag appears as a box with a plus sign along with the cursor. Data is copied to the target through the drop operation. 
Scroll The drop target is scrolling while the item is being dragged.
Link Data from the source of the item being dragged is linked to the target it is being dropped into.
All The data is moved and scrolled in the drop target

The only effects we are concerned with in this example is the Move and Copy Effects. When the user begins dragging, the delegated method below is called and it is here where we initiate the drag drop functionality by calling DoDragDrop. Do drag drop passes the data and the effect to initiate. We set the effect based on whether the user has pressed the control key or not.  In this example, we don't actually use the data, since it's part of the same control, so it isn't so important what the first parameter is. We just maintain what is being dragged in a field of our class. Note that the Node being dragged is determined from the ItemDragEventArg received in this method:

protected void treeView1_ItemDrag (object sender,System.WinForms.ItemDragEventArgs e)
{
// Remember the Item being dragged if it is a file node (ImageIndex == 2)
TreeNode aNode = (TreeNode)e.Item;
Bitmap bmp = imageList1.GetBitmap(2);
// Only drag if it is a file, where not dragging directories in this example
if (aNode.ImageIndex == 2)
{
StartNode = aNode; 
//The effect was previously set based on whether the ctrl key was pressed.
// If it was, the effect will be copy otherwise it will be move
// Set the state of the drag-drop operation, the state is a local enumeration in our class
if (CurrentEffect == DragDropEffects.Move)
{
CurrentState = States.Move;
}
else
{
CurrentState = States.Copy;
}
// DoDragDrop sets things in motion for the drag drop operation by passing the data and the current effect
// Data can be a bitmap, string or something that implements the IDataObject interface
this.DoDragDrop(imageList1.GetBitmap(aNode.ImageIndex), CurrentEffect);
}
}

Once the drag and drop operation is set in motion, we need to handle the events along the way.  Below we handle DragOver by hilighting folders as we drag over them.  DragEnter just maintains the effect:

protected void treeView1_DragOver (object sender, System.WinForms.DragEventArgs e)
{
// set the effect again to maintain the effect we set in the DoDragDrop, (Seems you have to do this, may be a bug)
e.Effect = CurrentEffect;
// Determine the node we are dragging over
// FindTreeNode is a local function of this class that determines the node from a point
TreeNode aNode = FindTreeNode(e.X, e.Y);
if (aNode != null)
{
// If the node is a folder, change the color of the background to dark blue to simulate selection
// Be sure to return the previous node to its original color by copying from a blank node
if ((aNode.ImageIndex == 1) || (aNode.ImageIndex == 0))
{
aNode.BackColor = Color.DarkBlue;
aNode.ForeColor = Color.White;
if ((OldNode != null) && (OldNode != aNode))
{
OldNode.BackColor = OriginalNode.BackColor;
OldNode.ForeColor = OriginalNode.ForeColor;
}
OldNode = aNode;
}
}
}
protected void treeView1_DragEnter (object sender, System.WinForms.DragEventArgs e)
{
e.Effect = CurrentEffect;
}

When we let go of the mouse while dragging, the DragDrop event is triggered.  Here we can copy or move our file node, depending on what effect was set.

// called last when mouse released during a drop
protected void treeView1_DragDrop (object sender, System.WinForms.DragEventArgs e)
{
// set a flag indicating if we are moving or not. If we are not moving, then we are copying
bool movingFile = (CurrentEffect == DragDropEffects.Move);
// determine the node we are dropping into from the coordinates of the DragEvent Arguement
TreeNode DropNode = FindTreeNode(e.X, e.Y);
// Reset the local state of the drag and the effect field
CurrentState = States.Idle;
CurrentEffect = DragDropEffects.Move;
// If the drop target is a folder (not a file), then perform drop operations
if (DropNode.ImageIndex != 2)
{
// it's a folder, drop the file
if (movingFile)
{
MoveFile(StartNode, DropNode);
// move the file from the startnode to the dropnode
}
else
{
CopyFile(StartNode, DropNode);
// copy the file from the startnode to the dropnode
}
this.Invalidate(new Region(this.ClientRectangle)); // redraw the treeview
treeView1.SelectedNode = DropNode; // select the drop node as the current selection
}
}

The CopyFile and MoveFile methods perform some directory and file operations from the System.IO namespace.  They also populate and depopulate the tree, accordingly. Below is the MoveFile method for doing a file move and restructuring the directory tree:

private void MoveFile(TreeNode Node1, TreeNode Node2)
{
string strdir1 = Node1.Parent.FullPath; // get the path of the source item
string strdir2 = Node2.FullPath; // get the path of the drop target
strdir1 = strdir1 + "\\" + Node1.Text; // create file paths using the name of the source item
strdir2 = strdir2 + "\\" + Node1.Text;
Directory.Move(strdir1, strdir2);
// use the static Directory Move command to move a file
TreeNode aNode = new TreeNode(Node1.Text, 2, 2); // create a new file node
Node1.Remove(); // remove the old file node
Node2.Nodes.Add(aNode); // add the new file node under the target directory node
}

I hope that this article reveals some of the mystery behind drag and drop. I'm still trying to figure out how to get the image to actually drag with the mouse (rather than a gray box) like it did in Visual C++.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
test by Vlad On February 21, 2007
test
Reply | Email | Modify 
drag-drop out of windows app by Vlad On February 21, 2007
Hi, What if I wanted to support drag-drop of out windows app. For example: User selects an image name from the drop-down and drags it to the desktop. The app resolves image location and copies it to the desktop. Thanks, Vlad
Reply | Email | Modify 
Re: drag-drop out of windows app by Michael On February 23, 2007

I am also very interested in learning how to drop raw data into a window. Like a data file, image, etc.

 

There must be a way to get the byte[] array that is dropped into a window...

Reply | Email | Modify 
Re: drag-drop out of windows app by Michael On February 23, 2007

http://www.ziggyware.com/readarticle.php?article_id=81

 

I have written an article on my site about how to drag and drop files into WinForms (even multiple selections).

Its very simple to do and only takes a couple lines of code.

The tutorial relates to the topic of XNA (XBOX 360 Development in C#) however its all basic WinForms coding.

Reply | Email | Modify 
Image by pratap On May 29, 2007
How to close a prior image when we want to display the second image in WPF Technologies of C# application
Reply | Email | Modify 
hello by spider1 On January 31, 2008
plz update article for 2.o
Reply | Email | Modify 
about drag and drop by karri On December 24, 2009
can u send me the code for these not in tree view we can select one we can drag that and if we dont need we can remove by using the mouse click selection.
Reply | Email | Modify 
drag and drop multiple rows of datagrid in windows application by suneetha On April 9, 2010
my requirement is to drag and drop multiple rows of datagrid in winforms. can any one help me out??
Reply | Email | Modify 
drag and drop toolbox by mouli On May 26, 2010
i want to insert a  toolbox in win form ,not all controls just 4 or 5 like textbox,label,datagridview ,etc...
it should have a drag and drop options .........
any help???
thankyou
Reply | Email | Modify 
Test by Khai On May 26, 2010
Could you help me solve this Test. It's too hard
Test Content:

Create a simple application with its associated sample code meet the Below Requirement?

1. A Windows Form Which contain a grid associated with a database table.

2. List of objects (globe and cube and cylinder) Which allow to be dragged & Dropped into a container on a form.

3. Users can define Dimensions and weight of the Above objects and containers.

4. Automatic display and total weight of the container after gravity center HAVING Dropped into several objects.

5. A container Should be able to be defined by users for its Dimensions and weight and gravity center.
Reply | Email | Modify 
IT by Analyn On January 15, 2011
I really like ur page..thank u..??
Reply | Email | Modify 
AUTHOR OF THIS CODE SUCKS A NGGR DIK by ass On December 10, 2011
HEY SHIT IN FACE AHOLE YOU CODE DOES NOT COMPILE AND YOU DUMB SOB YOU
Reply | Email | Modify 
BEAWARE THIS CODE POSTED IS CRAPOLA by ass On December 10, 2011
ANS DOES NOT COMPILEWOTH A CRAP VLAD HAS DIK UP GOATS AHOLE
Reply | Email | Modify 
HE MIKE GOLD HOW LONG YOU BEEN A DUMB AHOLE by ass On December 10, 2011
YOUR CODE IS CRAPOLA AND YOUR MAMA SUCKS GOAT DICK
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.