Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've got a form (similar to simple explorer) which contains treeView and listView.

I'd like to accomplish a multiple item selection from listView in one instance of a form and transfer them (with means of drag and drop) into second instance of same form, more precisely second form's listView.

The thing now works for only single item.

Any help would be greatly appreciated.

C#
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
      listView1.DoDragDrop(e.Item, DragDropEffects.Move); //works but only single element is transferred
      //listView1.DoDragDrop(listView1.SelectedItems, DragDropEffects.Move); //doesn't work
      /* doesn't work as well
      if (this.listView1.SelectedIndices.Count > 0)
      {
        List<ListViewItem>; elements = new List<ListViewItem>();
        foreach (int index in this.listView1.SelectedIndices)
        {
            elements.Add(this.listView1.Items[index]);
        }
        this.listView1.DoDragDrop(elements, DragDropEffects.Copy | DragDropEffects.Move);
      }
      */
}
private void listView1_DragDrop(object sender, DragEventArgs e)
{
      ListView files = (ListView)e.Data.GetData(typeof(ListView)); //works only for single element
      /* doesn't work (elements = null)
      List<ListViewItem> elements = new List<ListViewItem>();
      elements = e.Data.GetData(typeof(List<ListViewItem>)) as List<ListViewItem>;
      */
}


update:
When I open up two instances of the form and try to drag and drop a couple of items from one listview to another one in other instance I get this error:
Unable to cast COM object of type 'System.__ComObject' to class type 'SelectedListViewItemCollection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
here:

C#
foreach (ListViewItem current in (ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)))
                   {
                       listView1.Items.Add((ListViewItem)current.Clone());
                   }






My complete (still work in progress) code:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Management;
namespace DragAndDrop
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            treeView1.Nodes.Clear();
            foreach (DriveInfo p in DriveInfo.GetDrives())
            {
                if (p.IsReady)
                {
                    TreeNode pogon = new TreeNode();
                    pogon.Text = p.Name;
                    pogon.ImageIndex = 0;
                    pogon.SelectedImageIndex = 0;
                    pogon.Nodes.Add("");
                    treeView1.Nodes.Add(pogon);
                }
            }
        }
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            listView1.Clear();
            try
            {
                string[] datoteke = Directory.GetFiles(treeView1.SelectedNode.FullPath);
                foreach (string dat in datoteke)
                {
                    string[] podatkiDat = new string[2];
                    podatkiDat[0] = GetPathName(dat); //ime datoteke
                    podatkiDat[1] = dat; //celotna pot datoteke
                    FileInfo objFileSize = new FileInfo(dat);
                    ListViewItem nov = new ListViewItem(podatkiDat, 3);
                    listView1.Items.Add(nov);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        protected string GetPathName(string stringPath)
        {
            string[] stringSplit = stringPath.Split('\\');
            int _maxIndex = stringSplit.Length;
            return stringSplit[_maxIndex - 1];
        }
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
        }
        private void velikeIkoneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.LargeIcon;
        }
        private void seznamToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.List;
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ////listView1.Items.Remove(listView1.SelectedItems[0]);
            //if (listView1.SelectedItems.Count > 0)
            //{
            //    //foreach (ListViewItem l in listView1.SelectedItems)
            //    //{ }
            //    //MessageBox.Show(listView1.SelectedItems[0].Text);
            //    ListViewItem.ListViewSubItem aa = listView1.SelectedItems[0].SubItems[1]; //dobim pot
            //    //MessageBox.Show(listView1.SelectedItems[0].SubItems[1].Text);
            //}
        }
        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            //if(e.Data.GetDataPresent(DataFormats.FileDrop))
            // if (e.Data.GetDataPresent(DataFormats.Text))
            //if (e.Data.GetDataPresent(typeof(ListViewItem)))
            //e.Effect = DragDropEffects.Move; //ko postavimo izbrano datoteko nad listview se pod kurzurjem pojavi pravokotnik, ki simbolizira premikanje
            //e.Effect = DragDropEffects.Copy; //kopiranje, če je drugi disk
            //e.Effect = DragDropEffects.None;
            //if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
            //    e.Effect = e.AllowedEffect;
        }
        private void listView1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
            {
                if (e.Effect == DragDropEffects.Copy)
                {
                    foreach (ListViewItem current in (ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)))
                    {
                        listView1.Items.Add((ListViewItem)current.Clone());
                    }
                }
                else
                {
                    foreach (ListViewItem current in (ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)))
                    {
                        current.Remove();
                        listView1.Items.Add((ListViewItem)current);
                    }
                }
            }
        }
        private void listView1_MouseDown(object sender, MouseEventArgs e)
        {
        }
        private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            //listView1.DoDragDrop(e.Item, DragDropEffects.Move);
            listView1.DoDragDrop(listView1.SelectedItems, DragDropEffects.Copy);
            //ListViewItem[] myItemsT = new ListViewItem[listView1.SelectedItems.Count];
            //int i = 0;
            //foreach (ListViewItem myItemT in listView1.SelectedItems)
            //{
            //    myItemsT[i] = myItemT;
            //    i = i + 1;
            //}
            //this.DoDragDrop(new DataObject("System.Windows.Forms.ListViewItem()", myItemsT), DragDropEffects.Move);
        }
        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                TreeNode parentnode = e.Node;
                DirectoryInfo dr = new DirectoryInfo(parentnode.FullPath);
                parentnode.Nodes.Clear();
                foreach (DirectoryInfo dir in dr.GetDirectories())
                {
                    TreeNode node = new TreeNode();
                    node.Text = dir.Name;
                    node.ImageIndex = 1;
                    node.Nodes.Add(""); //dummy text
                    parentnode.Nodes.Add(node);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error!!");
            }
        }
        private void listView1_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
                e.Effect = e.AllowedEffect;
        }
    }
}
Posted
Updated 28-Dec-10 14:18pm
v6
Comments
JF2015 28-Dec-10 11:10am    
Fixed code formatting.

You should read up on how to implement drag and drop (see here: http://tinyurl.com/3xw7wtg[^])

You're biggest problem is that the ItemDrag is only going to add the actual item that was clicked on, not all of the selected items.

So, you need to decide how you're going to get all of the items into the DataObject that is being dragged. Drag and drop can get very complicated.

I'll provide a simple example though. I created a form with a ListView, a button, and a checkbox. The button just opens up a new instance of the form. The checkbox says whether or not to copy the item (if not checked, it will be moved).

The ListView is populated with items in the Form's load event.

To start the drag, I do:
C#
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
    listView1.DoDragDrop(listView1.SelectedItems,
                         checkBox1.Checked ? DragDropEffects.Copy : DragDropEffects.Move);
}



Then you have to handle the DragOver to set the effect.
C#
private void listView1_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
        e.Effect = e.AllowedEffect;
}


Then, you handle the DragDrop
C#
private void listView1_DragDrop(object sender, DragEventArgs e)
{
    if(e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
    {
        if (e.Effect == DragDropEffects.Copy)
        {
            foreach (ListViewItem current in (ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)))
            {
                listView1.Items.Add((ListViewItem)current.Clone());
            }
        }
        else
        {
            foreach (ListViewItem current in (ListView.SelectedListViewItemCollection)e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)))
            {
                current.Remove();
                listView1.Items.Add((ListViewItem)current);
            }
        }
    }
}



The different methods you use will depend on what you're trying to do. If it's a simple ListViewItem with only text, you may want to just create a string array and add that.
 
Share this answer
 
v2
Comments
punxx 28-Dec-10 20:09pm    
Thanks for your help.
When I open up two instances of the form and try to drag and drop a couple of items from one listview to another one in other instance I get this error:

Unable to cast COM object of type 'System.__ComObject' to class type 'SelectedListViewItemCollection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
You will be dragging ListViewItems and yet your code tries to GetData for ListView
C#
ListView files = (ListView)e.Data.GetData(typeof(ListView)); //works only for single element


although I am not sure that this will actually solve the problem.
 
Share this answer
 
Comments
Sandeep Mewara 28-Dec-10 12:14pm    
Comment from OP:
I'm sorry. I must have pasted something wrong. This line is working for single item in listView1_DragDrop event.

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900