从Combobox C#中选择默认项目

我的ComboBox项目集合中的项目很少,我想从此列表中选择一项并将其设置为默认项目 – 当应用程序启动时 – 此项目已在combobox中。

我正在尝试这样的事情:

SelectPrint11.SelectedIndex=2; 

但错误是:):

 System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex' 

编辑:

我现在无法添加评论..连接或其他问题..但在我的列表上有3个项目。 Printer1,Printer2,Printer3。 所有都添加在Combobox属性 – >项目 – >集合中

您可以使用SelectedIndex进行设置

 comboBox1.SelectedIndex= 1; 

要么

的SelectedItem

 comboBox1.SelectedItem = "your value"; // 

如果combobox中没有该值,则后者不会抛出exception

编辑

如果要选择的值不是特定的那么你会更好

 comboBox1.SelectedIndex = comboBox1.Items.Count - 1; 

请记住,C#中的集合是从零开始的(换句话说,集合中的第一个项目位于位置)。 如果列表中有两个项目,并且要选择最后一个项目,请使用SelectedIndex = 1

这意味着您的selectedindex超出了combobox中项目数组的范围。 combobox中的项目数组是从零开始的 ,因此如果您有2个项目,则它是项目0和项目1。

 private void comboBox_Loaded(object sender, RoutedEventArgs e) { Combobox.selectedIndex= your index; } 

或者,如果要在比较combobox后显示某些值

  foreach (var item in comboBox.Items) { if (item.ToString().ToLower().Equals("your item in lower")) { comboBox.SelectedValue = item; } } 

我希望它会有所帮助,它对我有用。

首先,转到comboBox所在的表单加载,

然后试试这段代码

comboBox1.SelectedValue = 0; //显示集合中的第1个项目