Drag and Drop from TreeView

This is pretty straight forward, in the sample code below it shows how to add a TreeView node with an image into a ListBox. You’ll need an ImageList loaded with images to link both the TreeView and ListBox to and set the ListView to a view that allows images, i.e ‘Tile’.

private TreeNode sourceNode;

private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
    sourceNode = (TreeNode)e.Item;

    if (sourceNode.Parent != null)
        DoDragDrop(sourceNode, DragDropEffects.Move);
}

private void DragEnter_Event(object sender, DragEventArgs e)
{
    if (e.Data.GetData(typeof(TreeNode)) != null)
        e.Effect = DragDropEffects.Move;
    else
        e.Effect = DragDropEffects.None;
}

private void listView1_DragDrop(object sender, DragEventArgs e)
{
    listView.Items.Add(sourceNode.Text, sourceNode.ImageIndex);
}

Just add the DragEnter event to the _DragEnter event of the controls you want to allow the DragDropEffects.Move to show on.

Advertisements