6

I have a function for setting items in a combobox and one item is to be set by default like

--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?

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Srivastava
  • 3,500
  • 12
  • 46
  • 74

1 Answers1

15

I've rewritten this answer to clarify some stuff.

First, the "default" text must be added as combo item as well. Usage of combo.Text property just adds descriptive text to combobox which is "lost" first time user do something with a control. If you like to permanently have "default" text in your combo, you must add it as an combobox item.

By the code you provided, just modify the

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

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

Finally, put

cboOperations.SelectedIndex = 0;
line at the end of code. By doing so, you're telling combobox to display your "default" item initially when the form (or control) loads.

One more thing. I'm not pretty sure what do you want to achieve with the code beyond setting combo items, but if you like to check what user selected use cboOperations.SelectedIndex property which contains currently selected item in combo. You can add simple

if(cboOperations.SelectedIndex == someIntValue){...}
The rest is your program logic ;)
Vexy
  • 1,274
  • 1
  • 12
  • 17