如何在C#中的2个列表框之间拖动多项?

时间:2015-05-18 20:07:14

标签: c# drag-and-drop listbox

我可以从listbox1拖动一个项目并将其拖放到listbox2但是当我从listbox1中选择多个项目时我该怎么办?

    private void FrmCh3_Load(object sender, EventArgs e)
    {
        listBox2.AllowDrop = true;

    }
    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {


        listBox1.DoDragDrop(listBox1.SelectedItem, DragDropEffects.Copy);

    }
    private void listBox2_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Copy;
    }

    private void listBox2_DragDrop(object sender, DragEventArgs e)
    {          
        listBox2.Items.Add(e.Data.GetData(DataFormats.Text));

    }

1 个答案:

答案 0 :(得分:1)

您可以简单地将整个SelectedItems属性设置为拖放数据:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    listBox1.DoDragDrop(listBox1.SelectedItems, DragDropEffects.Copy);
}

private void listBox2_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetData(typeof (ListBox.SelectedObjectCollection)) != null)
    {
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}

private void listBox2_DragDrop(object sender, DragEventArgs e)
{
    var items = (ListBox.SelectedObjectCollection)e.Data.GetData(typeof (ListBox.SelectedObjectCollection));
    foreach (var item in items)
    {
        listBox2.Items.Add(item);
    }
}