简体   繁体   中英

Selecting default item from Combobox C#

I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox .

I'm trying something like that:

SelectPrint11.SelectedIndex=2;

but error is:

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

Edit:

In mylist are 3 items, Printer1 , Printer2 , Printer3 . All are added in ComboBox Properties -> Items -> Collection

You can set using SelectedIndex

comboBox1.SelectedIndex= 1;

OR

SelectedItem

comboBox1.SelectedItem = "your value"; // 

The latter won't throw an exception if the value is not available in the combobox

EDIT

If the value to be selected is not specific then you would be better off with this

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

Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero ). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1 .

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

OR if you want to display some value after comparing into combobox

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

I hope it will help, it works for me.

This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based , so if you have 2 items, it's item 0 and item 1.

this is the correct form:

comboBox1.Text = comboBox1.Items[0].ToString();

U r welcome

first, go to the form load where your comboBox is located,

then try this code

comboBox1.SelectedValue = 0; //shows the 1st item in your collection

    ComboBox1.Text = ComboBox1.Items(0).ToString

此代码向您显示 Combobox1 在 Vb.net 中的第一项

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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