Click to See Complete Forum and Search --> : drag and drop from treeview to listview using C#


TheFortuneHunter
February 27th, 2009, 11:11 PM
Hi...

Could anyone show me the C# code to Drag and Drop from a Treeview to a Listview?

Thank You in advance...

toraj58
March 2nd, 2009, 07:26 AM
hopefully i have aleardy implemented such problem:

here is the code:


private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
treeView1.DoDragDrop(e.Item, DragDropEffects.Move);
string txt;
txt = null;

txt += e.Item.ToString();
textBox2.Text = txt;

}

private void listView1_DragEnter(object sender, DragEventArgs e)
{
// this code can be in DragOver also
if (e.Data.GetDataPresent(typeof(TreeNode)))
e.Effect = DragDropEffects.Move;
}

private void listView1_DragDrop(object sender, DragEventArgs e)
{

if (e.Data.GetDataPresent(typeof(TreeNode)))
{
TreeNode tn = (TreeNode) e.Data.GetData
(typeof(TreeNode));
listView1.Items.Add(tn.Text, tn.ImageIndex);
treeView1.Nodes.Remove(tn);
}
}


the workhorse of the code is in ItemDrag, DragEnter and DragDrop events.

dwaipeyan
March 5th, 2009, 04:05 AM
Hello

Can I have the code for in reverse implementation with duplicate check while adding to tree view.

Thanks,
Ranga

toraj58
March 5th, 2009, 10:18 AM
just reverse the usage of listview and treeview.
a little twist in the code will do the job for you.

toraj58
March 6th, 2009, 10:58 AM
i got time and wrote the code for you.
this time darg from listview to tree with duplicate check:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DragFromListToTree
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//listView1.AllowDrop = true;
treeView1.AllowDrop = true;
}

private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
listView1.DoDragDrop(e.Item, DragDropEffects.Move);

}

private void treeView1_DragEnter(object sender, DragEventArgs e)
{
// this code can be in DragOver also
if (e.Data.GetDataPresent(typeof(ListViewItem)))
e.Effect = DragDropEffects.Move;
}

private void treeView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(ListViewItem)))
{

ListViewItem li = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

bool dupplicate = false;

foreach (TreeNode tn in treeView1.Nodes)
{
if (tn.Text == li.Text) dupplicate = true;
}

if (!dupplicate)
{
treeView1.Nodes.Add(li.Text);
listView1.Items.Remove(li);
}
}
}

}
}