2013-10-08 15 views
3

我在这里有一个愚蠢的问题,但我无法解决它。问题是,当我以编程方式将数据绑定到组合框时,它会自动设置selectedItem,但我使用属性字段来添加项目,它不会设置selectedItem。Combobox选择事件自动触发当编程绑定数据源c#

我的问题是如何以编程方式绑定项目而不触发选定的事件(意味着它的行为就像使用不默认设置selectedItem的属性的绑定)?提前致谢。

实施例设置编程

串[]项= { “苹果”, “橙色”, “香蕉”}; comboBox1.DataSource = items;

当程序运行它看起来像这样(默认值被选择这是苹果):

enter image description here

实施例设置使用属性字段项(VS 2013)

enter image description here

然后它会看起来像这样(de故障值未选择):

enter image description here

回答

4

你可以退订,然后订阅事件,因为我认为,当你设置使用VisualStudio中的属性字段中的数据,所有设置将在订阅事件之前应用。

//unsubscribe the event handler (change the name of the event handler to your real name) 
ComboBox1.SelectedIndexChanged -= ComboBox1_SelectedIndexChanged 

//do your initialization 
string[] items = {"Apple", "Orange", "Banana"}; 
comboBox1.DataSource = items; 
comboBox1.SelectedIndex = -1; 

//subscribe to it again 
ComboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged 
+0

谢谢@博卢,这就是我想要的。 – overshadow

0

写ComboBox.SelectedIndex = -1 这将解决你的问题

+0

我之前尝试这个,它不会为我工作。它仍然会触发selectedIndexChanged事件 – overshadow

+0

尝试SelectionchangeCommited事件。 –

+0

好的,它不会触发事件,但它仍然显示在comboxBox的值。我认为这不是我想要的。无论如何,谢谢你@Palak Maheria – overshadow

0

如果不是writng这样的:

string[] items = {"Apple", "Orange", "Banana"}; 
comboBox1.DataSource = items; 

你会这样写:

string[] items = {"Apple", "Orange", "Banana"}; 
//comboBox1.Items.Clear(); 
comboBox1.Items.AddRange(items); 
相关问题