C#在表单的两个实例之间从listView拖放到列表视图 [英] C# drag and drop from/into listView between two instances of a form

查看:81
本文介绍了C#在表单的两个实例之间从listView拖放到列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单(类似于简单的资源管理器),其中包含treeView和listView.

我想在表单的一个实例中从listView完成多个项目的选择,并将它们(通过拖放的方式)转移到相同表单的第二个实例中,更确切地说是第二个表单的listView.

现在,该功能仅适用于单个项目.

任何帮助将不胜感激.

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.

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>;
      */
}



更新:
当我打开表单的两个实例并尝试将几个项目从一个列表视图拖放到另一个实例中的另一个列表时,出现此错误:
无法将类型为"System .__ ComObject"的COM对象转换为类类型为"SelectedListViewItemCollection".代表COM组件的类型的实例不能转换为不代表COM组件的类型.但是,只要基础COM组件支持对接口IID的QueryInterface调用,就可以将它们强制转换为接口.
此处:



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:

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:

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;
        }
    }
}

推荐答案

您应该阅读有关如何实现拖放的信息(请参见此处: ^ ] )

您最大的问题是ItemDrag仅将添加被单击的实际项目,而不是所有选中的项目.

因此,您需要确定如何将所有项目放入要拖动的DataObject中.拖放会变得非常复杂.

我将提供一个简单的示例.我创建了一个带有ListView,一个按钮和一个复选框的表单.该按钮仅打开表单的新实例.复选框说明是否要复制该项目(如果未选中,它将被移动).

ListView填充有Form的load事件中的项目.

要开始拖动,我要做:
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:
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
    listView1.DoDragDrop(listView1.SelectedItems,
                         checkBox1.Checked ? DragDropEffects.Copy : DragDropEffects.Move);
}




然后,您必须处理DragOver才能设置效果.




Then you have to handle the DragOver to set the effect.

private void listView1_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
        e.Effect = e.AllowedEffect;
}



然后,您处理DragDrop



Then, you handle the DragDrop

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);
            }
        }
    }
}




您使用的不同方法将取决于您要执行的操作.如果它是仅包含文本的简单ListViewItem,则您可能只想创建一个字符串数组并添加它.




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.


您将拖动ListViewItems,但是您的代码尝试将对于ListView
You will be dragging ListViewItems and yet your code tries to GetData for ListView
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.


这篇关于C#在表单的两个实例之间从listView拖放到列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆