Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 742
Elfoc Avatar asked Apr 12 '11 09:04

Elfoc


People also ask

How do I set a default ComboBox?

With a combo box, “default” isn't a useful property. To set the default value, use “DefaultSelectedItems” instead. This causes specified records to display by default. To set DefaultSelectedItems, use the Filter function for the same datasource you used for your Items property.

How do I reset a selection ComboBox?

The easiest way to clear the second combobox is to just use Reset(). That will clear all the current selections and reset the combobox to its default selection.

Is the default event of ComboBox control?

By default, DropDownStyle property of a Combobox is DropDown. In this case user can enter values to combobox. When you change the DropDownStyle property to DropDownList, the Combobox will become read only and user can not enter values to combobox.

Is used to set the selected item in a ComboBox?

When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index.


2 Answers

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; 
like image 166
V4Vendetta Avatar answered Oct 19 '22 23:10

V4Vendetta


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.

like image 36
Michael Petrotta Avatar answered Oct 20 '22 00:10

Michael Petrotta