WinForm实现简单的拖拽功能(C#)

用到了ListBox和TreeView两个控件,ListBox作为数据源,通过拖拽其中的数据放置到TreeView上,自动添加一个树节点

    ListBox控件的MouseDown用于获取要拖拽的值并调用DoDragDrop方法

    private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            //调用DoDragDrop方法
            if (this.listBox1.SelectedItem != null)
            {
                this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Copy);
            }
        }

 

TreeView控件的DragEnter和DragDrop事件用于接收数据并添加为树节点

private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            //设置拖拽类型(这里是复制拖拽)
            e.Effect = DragDropEffects.Copy;
        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            //获取值
            string item = (string)e.Data.GetData(e.Data.GetFormats()[0]);

            this.treeView1.Nodes.Add(item);
        }

posted @ 2016-02-18 09:51  龙骑科技  阅读(665)  评论(0编辑  收藏  举报