简体   繁体   English

将项目添加到ComboBox并选择相同的项目

[英]Adding a Item to ComboBox and Selecting the same item

There is a Empty ComboBox to which I will be adding a Item and I want to select the same Item automatically. 有一个空组合框,我要向其中添加一个项目,并且我想自动选择相同的项目。 Currently I am using the code below and its working. 目前,我正在使用下面的代码及其工作。

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

But I feel this method is quite naive. 但是我觉得这种方法很幼稚。 Is there a method to select the added item automatically. 有没有一种方法可以自动选择添加的项目。 I tried searching for the same in google but couldn't find any satisfying answers. 我尝试在Google中搜索相同内容,但找不到任何令人满意的答案。

Thanks in advance. 提前致谢。

Another way of doing the same is 另一种方法是

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

OR if you are using ComboboxItem then you can use 或者,如果您使用的是ComboboxItem,则可以使用

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

I don't really see the issue here, the best thing you can do is to remove the if statement containing the count as its not exactly necessary. 我在这里没有真正看到问题,您最好的办法是删除包含count的if语句,因为它不是完全必要的。

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

Its quick, its easy and it does what you want it to do. 它快速,简单并且可以完成您想要的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM