Setting a default item in a combo box

I have a function to set elements in a combobox, and one element should be set by default, for example

- SELECT LIST -

public void SetOperationDropDown() { int? cbSelectedValue = null; if(cmbOperations.Items.Count == 0) { //This is for adding four operations with value in operation dropdown cmbOperations.Items.Insert(0, "PrimaryKeyTables"); cmbOperations.Items.Insert(1, "NonPrimaryKeyTables"); cmbOperations.Items.Insert(2, "ForeignKeyTables"); cmbOperations.Items.Insert(3, "NonForeignKeyTables"); cmbOperations.Items.Insert(4, "UPPERCASEDTables"); cmbOperations.Items.Insert(5, "lowercasedtables"); //ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-. cmbOperations.Text = "-SELECT OPERATIONS-"; } else { if(!string.IsNullOrEmpty("cmbOperations.SelectedValue")) { cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue); } } //Load the combo box cmbOperations again if(cbSelectedValue != null) { cmbOperations.SelectedValue = cbSelectedValue.ToString(); } } 

Can anyone suggest a way to do this?

+6
c # visual-studio winforms
source share
1 answer

I rewrote this answer to clarify some things.

First, the default text should be added as a combo element. Using the combo.Text property simply adds descriptive text to the combobox, which is "lost" the first time the user does something with the control. If you like forever having the default text in your combo, you should add it as a combobox element.

In the code you provided, just change

 cmbOperations.Text = "-SELECT OPERATIONS-"; 
to
 cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-"); 

Note that this way you add the "-SELECT OPERANDS-" element to the position of the 0th (read first) in the list. Also make sure that all of your next items are increased by 1, because now they are moved with one space in the list.

Finally put the line

 cboOperations.SelectedIndex = 0; 
at the end of the code. By doing so, you are reporting that combobox displays your default item when loading a form (or control).

One more thing. I'm not quite sure what you want to achieve with code that does not install combo elements, but if you like to check which user has selected, use the cboOperations.SelectedIndex property, which contains the currently selected element in combo. You can add simple

 if(cboOperations.SelectedIndex == someIntValue){...} 
The rest is your program logic;)
+14
source share

All Articles