从Combobox C#中选择默认项目

Elf*_*foc 30 .net c# combobox winforms

我的ComboBox物品集合中有很少的物品,我想从这个列表中选择一个项目并将其设置为默认项目 - 当应用程序启动时 - 此项目已经打开comboBox.

我正在尝试这样的事情:

SelectPrint11.SelectedIndex=2;
Run Code Online (Sandbox Code Playgroud)

但错误是:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'
Run Code Online (Sandbox Code Playgroud)

编辑:

mylist3个项目,Printer1,Printer2,Printer3.全部都加入了ComboBox Properties -> Items -> Collection

V4V*_*tta 67

您可以使用SelectedIndex进行设置

comboBox1.SelectedIndex= 1;
Run Code Online (Sandbox Code Playgroud)

要么

的SelectedItem

comboBox1.SelectedItem = "your value"; // 
Run Code Online (Sandbox Code Playgroud)

如果组合框中没有该值,则后者不会抛出异常

编辑

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

comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`SelectedIndex`属性,则计数从0开始,而不是1. (11认同)

Mic*_*tta 7

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