Search code examples
c#winformsdrag-and-droplistboxtreeview

Drag a item from Treeview to ListBox on Windows Forms (C#)


I'm Writing an application in Windows forms with a File Explorer TreeView and I need a way to get the Node.FullPath in string to a ListBox using Drag and Drop.

yesterday I found this question about it:

C# Drag & drop from listbox to treeview

but I need the exactly oposite and maybe a way to hold Shitf and do the selection with more than one Node to proceed drag and drop with them


Solution

  • Drag&Drop is the same concept, there is the code that I used to make it happen.

        private void tvDiretorios2_ItemDrag(object sender, ItemDragEventArgs e)
        {
            //pega os Selecionados e colocar em uma lista
            List<string> listaSelecionados = new List<string>();
            foreach (TreeNode tN in tvDiretorios.SelectedNodes)
            {
                listaSelecionados.Add(tN.FullPath.ToString());
            }
            DoDragDrop(listaSelecionados, DragDropEffects.Move);
        }
    
        private void tvDiretorios2_DragOver(object sender, DragEventArgs e)
        {
            //Depois de DoDragDrop Existi- 2°Passo. Confirma que o que foi puxado é uma lista
            if (e.Data.GetDataPresent(typeof(List<string>)))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }
    
    
    
    
        /** EVENTOS DROP DA LISTA */
        private void lbConvertidas_DragEnter(object sender, DragEventArgs e)
        {
            //Determina se o o objeto pode ser arrastado para o lbConvertidas
            if(e.Data.GetDataPresent(typeof(List<string>)))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }
    
        private void lbConvertidas_DragDrop(object sender, DragEventArgs e)
        {
            //Toma alguma ação quando ele for solto
            //Importar(); -- Ação Principal
            var lista = e.Data.GetData(typeof(List<string>)) as List<string>;
            if (lista != null)
                lbConvertidas.Items.AddRange(lista.ToArray()); //será convertido 
        }
    

    But to select more then One Node I used an alternative TreeView component, source link is down below.

    http://www.arstdesign.com/articles/treeviewms.html

    I Created a simple checking routine just to know that I'm in the right direction.

     private void BuscarSelecionados()
        {
            foreach (TreeNode tN in tvDiretorios2.SelectedNodes)
            {
                MessageBox.Show(tN.FullPath.ToString(), "Atenção");
            }
        }
    

    The key is using this alternative TreeNode Component.

    Thanks anyway to the ones who tried to help...and the ones you didn't...