代码改变世界

C# 多个(N个)ListBox之间的拖动方法

2012-05-25 11:16  Andrew.Wangxu  阅读(1106)  评论(1编辑  收藏  举报

需求说明:在窗体界面中有多个ListBox要实现之间的数据拖动,下面是封装的一个方法,实现N个ListBox的数据拖放操作。

可任意拖放数据到任意的ListBox

 

附上截图、代码、示例项目文件:

 

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ListboxDrop
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ListBoxDrop(listBox1, listBox2,listBox3,listBox4,listBox5,listBox6);
        }


        /// <summary>
        /// 完成所有的listBox之间的数据拖动
        /// </summary>
        /// <param name="listboxs">ListBox控件列表</param>
        private void ListBoxDrop(params ListBox[] listboxs)
        {
            foreach (var lst in listboxs)
            {
                lst.AllowDrop = true;
                lst.MouseDown += new MouseEventHandler(lst_MouseDown);
                lst.DragOver += new DragEventHandler(lst_DragOver);
                lst.DragDrop += new DragEventHandler(lst_DragDrop);
            }
        }

        //拖放完成的操作
        void lst_DragDrop(object sender, DragEventArgs e)
        {
            ListBox lst = (ListBox)sender;
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                object item = (object)e.Data.GetData(
                    DataFormats.StringFormat);

                lst.Items.Add(item);
            }
        }

        //拖放到控件上时
        void lst_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        //鼠标按下
        void lst_MouseDown(object sender, MouseEventArgs e)
        {
            ListBox lst = (ListBox)sender;
            if (lst.Items.Count == 0 || e.Button != MouseButtons.Left || lst.SelectedIndex == -1)
                return;

            int index = lst.SelectedIndex;
            object item = lst.Items[index];
            DragDropEffects dde = DoDragDrop(item,
                DragDropEffects.All);

            if (dde == DragDropEffects.All)
            {
                lst.Items.RemoveAt(lst.IndexFromPoint(e.X, e.Y));
            }
        }


    }
}

 

注意:使用方法 ListBoxDrop 的时候只需要调用一次即可!!

项目下载(vs2010):https://files.cnblogs.com/andrew-blog/ListboxDrop.rar

参考:http://www.wxzzz.com/?id=94