Can I drag from ListView to TreeView in Winforms?

If this is not possible, I can also use 2 TreeView controls. I just won't have a hierarchy in the second TreeView control. It will act as some kind of repository.

Any sample code or tutorial will be very helpful.

+3
source share
1 answer

ListView doesn't support drag-and-drop naturally, but you can enable it with a bit of code:

http://support.microsoft.com/kb/822483

Here is an example that specifically performs drag-and-drop from ListViewto TreeView(this is the "Exchange of experience" link, so just wait a few seconds and then scroll down to find the answers):

http://www.experts-exchange.com/Programming/Languages/.NET/Visual_CSharp/Q_22675010.html

: :

  • . ( listview listView1, treeview tvMain)
  • AllowDrop true.
  • ItemDrag

private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            listView1.DoDragDrop(listView1.SelectedItems, DragDropEffects.Copy);
        }

"drop". DragEnter :

private void tvMain_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

. . ( ) node (, node , !)

DragDrop :

private void tvMain_DragDrop(object sender, DragEventArgs e)
        {
            TreeNode n;

            if (e.Data.GetDataPresent("System.Windows.Forms.ListView+SelectedListViewItemCollection", false))
            {
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                TreeNode dn = ((TreeView)sender).GetNodeAt(pt);
                ListView.SelectedListViewItemCollection lvi = (ListView.SelectedListViewItemCollection)e.Data.GetData("System.Windows.Forms.ListView+SelectedListViewItemCollection");

                foreach (ListViewItem item in lvi)
                {
                    n = new TreeNode(item.Text);
                    n.Tag = item;

                    dn.Nodes.Add((TreeNode)n.Clone());
                    dn.Expand();
                    n.Remove();
                }
            }
        }

, GiveFeedback ListView:

private void listView1_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            e.UseDefaultCursors = false;

            if (e.Effect == DragDropEffects.Copy)
            {
                Cursor.Current = new Cursor(@"myfile.ico");
            }
        }

myfile.ico , .exe.

. , .

+6

Source: https://habr.com/ru/post/1793124/


All Articles