Reputation: 3689
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
Upvotes: 46
Views: 227311
Reputation: 38200
You can set using SelectedIndex (which uses a zero-based index)
comboBox1.SelectedIndex = 0;
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;
Upvotes: 94
Reputation: 29
this is the correct form:
comboBox1.Text = comboBox1.Items[0].ToString();
U r welcome
Upvotes: 2
Reputation: 11
ComboBox1.Text = ComboBox1.Items(0).ToString
This code is show you Combobox1 first item in Vb.net
Upvotes: -1
Reputation: 11
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
Upvotes: 0
Reputation: 780
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.
Upvotes: 3
Reputation: 63190
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.
Upvotes: 2
Reputation: 60902
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
.
Upvotes: 8