【问题标题】:Adding a Item to ComboBox and Selecting the same item向 ComboBox 添加项目并选择相同的项目
【发布时间】:2014-01-16 11:34:21
【问题描述】:

有一个空组合框,我将向其中添加一个项目,并且我想自动选择相同的项目。 目前我正在使用下面的代码及其工作。

    twComboBox1.Items.Add(ComboBoxItem);
            if(twComboBox1.Items.Count > 0)
               twComboBox1.SelectedIndex = 0;

但我觉得这种方法很幼稚。有没有一种方法可以自动选择添加的项目。我尝试在谷歌中搜索相同的内容,但找不到任何令人满意的答案。

提前致谢。

【问题讨论】:

  • 您不需要检查Count,因为您已保证添加了一个项目。 Add 将返回新添加项目的索引。有什么想法吗?

标签: c# .net drop-down-menu combobox


【解决方案1】:

另一种方法是

twComboBox1.Items.Add(ComboBoxItem);
twComboBox1.SelectedItem = ComboBoxItem;

或者,如果您使用的是ComboboxItem,那么您可以使用

twComboBox1.Items.Add(ComboBoxItem);
ComboBoxItem.IsSelected = true;

【讨论】:

    【解决方案2】:

    我没有真正看到这里的问题,你能做的最好的事情是删除包含计数的 if 语句,因为它不是完全必要的。

     twComboBox1.Items.Add(ComboBoxItem);
     twComboBox1.SelectedIndex = 0;
    

    它快速、简单,它可以做你想做的事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多