2013-04-03 82 views
0

在以下代码中抛出异常的可能原因是什么?ListBox.SelectedItem拒绝设置

var oldItem = this.MyListBox.SelectedItem; 

if (this.MyListBox.Items.Contains(newItem)) 
{ 
    this.MyListBox.SelectedItem = newItem; 

    if (this.MyListBox.SelectedItem != newItem && this.MyListBox.SelectedItem == oldItem) 
     throw new ApplicationException("WTF?"); 
} 

在任何时候都没有引发ListBox.SelectionChanged事件。

编辑:oldItem和newItem是相同类型的简单业务对象。它们不是null。

+0

@Matt你的newItem是什么 - 你是如何发起它的? – Alex

+0

这是在执行什么? – Clint

+0

多线程是最明显的猜测 - 其他线程修改选定的项目,而你的线程通过条件 –

回答

0

您需要可以使用SetSelected方法,像这样:

MyListBox.SetSelected(index, true); 

或把它放在项目本身,像这样:

MyListBox.Items(index).Selected = true; 

我不知道什么是newItem在你的问题,因此您需要在列表中标识它的索引,并将其放在上述代码段中的index的位置。