将事件中的发件人设置为变量

时间:2014-11-14 22:25:26

标签: c# winforms events listbox

我有3个与拖放有关的事件。

    object originalSender;

    private void lstBox_MouseDown(object sender, MouseEventArgs e)
    {
        ListBox curListBox = sender as ListBox;
        if (curListBox.SelectedItem == null) return;
        //this.lstLeft.DoDragDrop(this.lstLeft.SelectedItem, DragDropEffects.Move);
        curListBox.DoDragDrop(curListBox.SelectedItem, DragDropEffects.Copy);
        originalSender = sender;
    }

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

    private void lstBox_DragDrop(object sender, DragEventArgs e)
    {
        var obj = e.Data.GetData(e.Data.GetFormats()[0]);

        if (typeof(DataGridViewColumn).IsAssignableFrom(obj.GetType()))
        {
            ListBox curListBox = sender as ListBox;
            Point point = curListBox.PointToClient(new Point(e.X, e.Y));
            int index = curListBox.IndexFromPoint(point);
            if (index < 0)
                if (curListBox.Items.Count > 0)
                    index = curListBox.Items.Count - 1;
                else
                    index = 0;
            ((ListBox)(originalSender)).Items.Remove(obj);
            curListBox.Items.Insert(index, obj);
        }

问题在于&#34; originalSender&#34;运行lst_DragDrop方法时为null。我确定它是因为我引用了收集垃圾的发送方对象因此为空。如何引用作为发件人的列表框。

我有3个ListBox都使用这个方法所以我需要知道哪一个被选中。

1 个答案:

答案 0 :(得分:1)

尝试在调用originalSender = sender之前移动DoDragDrop语句; DoDragDrop在同一个线程上启动一个新的消息泵,因此当前该语句在拖放操作结束之前不会执行。


作为旁注:

  

我确定它是因为我引用了收集垃圾的发送方对象,因此为空

不,那是不可能的。你得到了它:垃圾收集器永远不会将对象引用设置为null,它只是收集不再引用的对象。

相关问题