C# Drag and Drop From listBox

▼魔方 西西 提交于 2019-11-29 02:38:20

Here's a fairly quick hack approach to gaining the functionality you want:

public object lb_item = null;



private void listBox1_DragLeave(object sender, EventArgs e)
{
    ListBox lb = sender as ListBox;

    lb_item = lb.SelectedItem;
    lb.Items.Remove(lb.SelectedItem);
}

private void listBox1_DragEnter(object sender, DragEventArgs e)
{       
    if (lb_item != null)
    {
        listBox1.Items.Add(lb_item);
        lb_item = null;
    }
}


private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    lb_item = null;

    if (listBox1.Items.Count == 0)
    {
        return;
    }                

    int index = listBox1.IndexFromPoint(e.X, e.Y);
    string s = listBox1.Items[index].ToString();
    DragDropEffects dde1 = DoDragDrop(s, DragDropEffects.All);      
}

private void Form1_DragDrop(object sender, DragEventArgs e)
{            
    lb_item = null;
}

Every time the user drags an item out of the box, it's saved temporarily until the user drops it somewhere else or mouses down on a new item in the list. Note the important part of this is detecting when and where the user let's go of that mouse, which is the rationale behind handling the DragDrop event of Form1, the parent of listBox1.

Depending on the sophistication and density of the rest of your layout, where you handle DragDrop could be much different for you. This is why it's kind of "hacky", but it's also quite simple. It shouldn't matter, though, where or how many times you null lb_item since it pertains only to that specific ListBox.

I suppose another way to do it would be to track the user's mouse states and act accordingly, which may be more appropriate for you if it's inconceivable to handle a lot of DragDrop stuff.

EDIT: If you wanted to be REAL thorough, you could enumerate through every control of the base form using foreach and programmatically append a handler for the DragDrop event to that control, then remove it when done... but that may be getting a little nutty. I'm sure someone has a better approach.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!