Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
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# » Imlememnting Drag and Drop in ListView Controls

Imlememnting Drag and Drop in ListView Controls

Drag and Drop operations in Windows can be achieved using 3 simple events - DragEnter, DragLeave, and DragDrop.

Page Views : 66101
Downloads : 1651
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:
DragDropListViewCode.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Drag and Drop operations in Windows can be achieved using 3 simple events - DragEnter, DragLeave, and DragDrop. The example provided in this articles shows you how to drag and drop items from one ListView control to another.

Important: If you plan to cut and paste the source code from this article , please make sure to set the AllowDrop option to True in the properties for the listView control.

Drag Data

Begin the Drag operation using

listView2.DoDragDrop(str, DragDropEffects.Copy | DragDropEffects.Move );

in this case the the drag is set to either copy or move. The example works by dragging a text object.

However any type of object can be used for dragging.

Drop Data

Use the DragEnter function to perform the type of drop operation.

private void listView1_DragEnter(object sender,System.Windows.Forms.DragEventArgs e)
{
if(e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void listView1_DragEnter(object sender,System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}

In this case the effects are either copy or none.

Here is the complete listing of the DragDrop Class

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace ODLV
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.ListView listView2;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
///
/// Required designer variable.
///
private System.ComponentModel.Container components = null;
bool lv1_mdown = false ;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader5;
bool lv2_mdown = false;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.splitter1 = new System.Windows.Forms.Splitter();
this.listView2 = new System.Windows.Forms.ListView();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader5 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// listView1
//
this.listView1.AllowDrop = true;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,this.columnHeader3});
this.listView1.Dock = System.Windows.Forms.DockStyle.Top;
this.listView1.FullRowSelect = true;
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(232, 176);
this.listView1.TabIndex = 0;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listView1_MouseDown);
this.listView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView1_DragDrop);
this.listView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView1_DragEnter);
this.listView1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.listView1_MouseMove);
//
// columnHeader1
//
this.columnHeader1.Text = "COL1";
this.columnHeader1.Width = 100;
//
// columnHeader3
//
this.columnHeader3.Text = "COL2";
this.columnHeader3.Width = 100;
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter1.Location = new System.Drawing.Point(0, 176);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(232, 3);
this.splitter1.TabIndex = 1;
this.splitter1.TabStop = false;
//
// listView2
//
this.listView2.AllowDrop = true;
this.listView2.Columns.AddRange(new System.Windows.Forms.ColumnHeader[]
{
this.columnHeader2,this.columnHeader5});
this.listView2.Cursor = System.Windows.Forms.Cursors.Arrow;
this.listView2.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView2.FullRowSelect = true;
this.listView2.Location = new System.Drawing.Point(0, 179);
this.listView2.MultiSelect = false;
this.listView2.Name = "listView2";
this.listView2.Size = new System.Drawing.Size(232, 226);
this.listView2.TabIndex = 2;
this.listView2.View = System.Windows.Forms.View.Details;
this.listView2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listView2_MouseDown);
this.listView2.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView2_DragDrop);
this.listView2.DragEnter = new System.Windows.Forms.DragEventHandler(this.listView2_DragEnter);
this.listView2.MouseMove += new System.Windows.Forms.MouseEventHandler(this.listView2_MouseMove);
//
// columnHeader2
//
this.columnHeader2.Text = "COL1";
this.columnHeader2.Width = 100;
//
// columnHeader5
//
this.columnHeader5.Text = "COL2";
this.columnHeader5.Width = 100;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(232, 405);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.listView2,this.splitter1,this.listView1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}

#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
ImageList il = new ImageList();
il.Images.Add(
new System.Drawing.Icon("D:\\smk\\odlv\\tick.ico"));
listView1.SmallImageList = il ;
ImageList i2 =
new ImageList();
i2.Images.Add(
new System.Drawing.Icon("D:\\smk\\odlv\\key04.ico"));
listView2.SmallImageList = i2 ;
string[] items = new string[2];
items[0] = "LA" ; items[1] = "Los Angeles";
listView1.Items.Add(
new ListViewItem(items,0));
items[0] = "WA" ; items[1] = "Seattle";
listView1.Items.Add(
new ListViewItem(items,0));
items[0] = "IL" ; items[1] = "Chicago";
listView1.Items.Add(
new ListViewItem(items,0));
items[0] = "FR" ; items[1] = "Paris";
listView2.Items.Add(
new ListViewItem(items,0));
items[0] = "BR" ; items[1] = "London";
listView2.Items.Add(
new ListViewItem(items,0));
items[0] = "IN" ; items[1] = "Mumbai";
listView2.Items.Add(
new ListViewItem(items,0));
}
private void listView1_DragDrop(object sender,System.Windows.Forms.DragEventArgs e)
{
string textBox1 = e.Data.GetData(DataFormats.Text).ToString();
string[] items = textBox1.Split(',');
listView1.Items.Add(
new ListViewItem(items,0));
lv1_mdown =
false ;
lv2_mdown =
false ;
}
private void listView2_DragDrop(object sender,System.Windows.Forms.DragEventArgs e)
{
string textBox1 = e.Data.GetData(DataFormats.Text).ToString();
string[] items = textBox1.Split(',');
listView2.Items.Add(
new ListViewItem(items,0));
lv2_mdown =
false ;
lv1_mdown =
false ;
}
private void listView2_DragEnter(object sender,System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void listView1_DragEnter(object sender,System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void listView1_MouseMove(object sender,System.Windows.Forms.MouseEventArgs e)
{
if ( ! lv1_mdown ) return ;
if ( e.Button == MouseButtons.Right ) return ;
string str = GetItemText(listView1) ;
if ( str == "" ) return ;
listView1.DoDragDrop(str , DragDropEffects.Copy | DragDropEffects.Move ) ;
}
private void listView2_MouseMove(object sender,System.Windows.Forms.MouseEventArgs e)
{
if ( ! lv2_mdown ) return ;
if ( e.Button == MouseButtons.Right ) return ;
string str = GetItemText(listView2) ;
if ( str == "" ) return ;
listView2.DoDragDrop(str, DragDropEffects.Copy | DragDropEffects.Move ) ;
}
private void listView1_MouseDown(object sender,System.Windows.Forms.MouseEventArgs e)
{
lv1_mdown =
true ;
}
private void listView2_MouseDown(object sender,System.Windows.Forms.MouseEventArgs e)
{
lv2_mdown =
true ;
}
public string GetItemText(ListView LVIEW)
{
int nTotalSelected = LVIEW.SelectedIndices.Count;
if ( nTotalSelected <= 0 ) return "";
IEnumerator selCol = LVIEW.SelectedItems.GetEnumerator();
selCol.MoveNext() ;
ListViewItem lvi = (ListViewItem)selCol.Current;
string mDir = "";
for ( int i=0; i < lvi.SubItems.Count;i++)
mDir += lvi.SubItems[i].Text +",";
mDir = mDir.Substring(0,mDir.Length-1);
return mDir ;
}
}
}

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
 
Shripad Kulkarni
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
Great Job by Xhiko On October 25, 2009
You do the great job.
Reply | Email | Modify 
Full of holes by Mitch On April 27, 2010
Horrible example
Reply | Email | Modify 
I'm trying to implement drawing with drag and drop in silverlight by farhad On June 11, 2010
Hi, i;m trying to implement drawing with drag and drop in silverlight, any resource and ideas, i'm looking forward to any suggestion..


https://mutiarar06.student.ipb.ac.id
Reply | Email | Modify 
hello by Kamlesh Kumar On August 11, 2010
sir can u tell me the code for creating windows explore in C#.net and how to save the data from windows explorer to my sql  with OdbcConnectivity using drag and drop operation on the form    

reply soon urgent requirement my email id is sati.kamleshkumar@gmail.com
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.