以编程方式绑定数据源c#时,Combobox选择了事件自动触发器

时间:2013-10-08 09:38:35

标签: c# combobox

我这里有一些愚蠢的问题,但我无法解决。问题是,当我以编程方式将组合框与数据绑定时,它将自动设置selectedItem但我使用属性字段添加它不会设置selectedItem的项目。

我的问题是如何在不触发所选事件的情况下以编程方式绑定项目(意味着它的行为类似于使用默认情况下未设置selectedItem的属性绑定)?提前谢谢。

以编程方式设置示例

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

当程序运行时,它将如下所示(选择默认值为Apple ):

enter image description here

使用属性字段(VS 2013)设置项目的示例

enter image description here

然后它看起来像这样(未选择默认值):

enter image description here

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果不是这样写,那该怎么办:

string[] items = {"Apple", "Orange", "Banana"}; 
comboBox1.DataSource = items;
你会写下这个:

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