开发者

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开发者_StackOverflow社区 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 is the correct form:

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

U r welcome


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.


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

This code is show you Combobox1 first item in Vb.net

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜