【问题标题】:Combobox selected event auto trigger when programatically bind the datasource c#以编程方式绑定数据源c#时,组合框选择事件自动触发
【发布时间】:2013-10-08 09:38:34
【问题描述】:

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

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

以编程方式设置的示例

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

程序运行时会如下所示(默认选择Apple):

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

然后会是这个样子(默认值没有选择):

【问题讨论】:

    标签: c# combobox


    【解决方案1】:

    您可以取消订阅然后订阅该事件,因为我认为当您使用 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
    

    【讨论】:

    • 谢谢@Bolu,这就是我想要的。
    【解决方案2】:

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

    【讨论】:

    • 我以前试过这个,它对我不起作用。它仍然触发 selectedIndexChanged 事件
    • 尝试 SelectionchangeCommited 事件。
    • 好的,它适用于不触发事件,但它仍然显示comboxBox的值。我想这不是我想要的。无论如何,谢谢@Palak Maheria
    • 要停止在组合框中显示第一个项目,您可以使用 ComboBox.SelectedIndex = - 1
    【解决方案3】:

    如果不写这个会怎样:

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

    你会这样写:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      相关资源
      最近更新 更多