ListBox Drag & Drop

摘要:ListBox Drag & Drop

ListBox 互相拖曳彼此的內容


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

namespace ListBoxTest
{
    public partial class Form1 : Form
    {
        enum LB_SRC { SRC, DEST};
        
        public Form1()
        {
            InitializeComponent();
            lbSrc.AllowDrop = true;
            lbDest.AllowDrop = true;
        }

        private void lbSrc_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (lbSrc.SelectedIndex > -1)
                {
                    lbSrc.DoDragDrop(LB_SRC.SRC, DragDropEffects.All);
                }
            }
        }

        private void lbDest_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(LB_SRC)))
            {
                LB_SRC src = (LB_SRC)e.Data.GetData(typeof(LB_SRC));
                if (src == LB_SRC.SRC)
                    e.Effect = DragDropEffects.All;
            }
        }

        private void lbDest_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(LB_SRC)))
            {
                LB_SRC src = (LB_SRC)e.Data.GetData(typeof(LB_SRC));
                if (src == LB_SRC.SRC)
                {
                    string a = lbSrc.SelectedItem as string;
                    lbDest.Items.Add(a);
                    lbSrc.Items.Remove(a);
                }
            }
        }

        private void lbSrc_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(LB_SRC)))
            {
                LB_SRC src = (LB_SRC)e.Data.GetData(typeof(LB_SRC));
                if (src == LB_SRC.DEST)
                    e.Effect = DragDropEffects.All;
            }
        }

        private void lbDest_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (lbDest.SelectedIndex > -1)
                {
                    lbDest.DoDragDrop(LB_SRC.DEST, DragDropEffects.All);
                }
            }
        }

        private void lbSrc_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(LB_SRC)))
            {
                LB_SRC src = (LB_SRC)e.Data.GetData(typeof(LB_SRC));
                if (src == LB_SRC.DEST)
                {
                    string a = lbDest.SelectedItem as string;
                    lbSrc.Items.Add(a);
                    lbDest.Items.Remove(a);
                }
            }
        }
    }
}