Behaviour of combo-boxes items, will they perform their actions if a previous variable defines what combo-box i'm in?

StackOverflow https://stackoverflow.com/questions/23455741

  •  15-07-2023
  •  | 
  •  

Question

It's the following, i have 1 combo-box with item1 and item2

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
    { 

        if (ComboBox1.SelectedItem == "item1")
        {
            variableA = 0;
        }
        else if (ComboBox1.SelectedItem == "item2")
        {
             variableA = 1;
        }
    }

and early in the program i have another variable that sets what item the combobox is in, for example

int variablecomboboxitem = 1;

if (variablecomboboxitem == 1) {ComboBox1.SelectedItem = "item1"} 
else if (variablecomboboxitem == 2 ){ComboBox1.SelectedItem = "item2"}

but, for diverse reasons i might need to start with variablecomboboxitem = 2;

the question is.. when i set the variablecomboboxitem = 1 early on the program, the item1 will show up in the combobox, but will it load variableA = 0??? or will he just set the item on the combobox???

if he doesn't load the variableA value, how can i make it so that he performs the actions after the combo-box item?

Was it helpful?

Solution

If I'm understanding the question properly, you're essentially asking if the SelectedIndexChanged event will be raised if you set the selected index programmatically.

The answer is yes. Setting the selected index of a combo box programmatically (e.g. by modifying the SelectedIndex property in the constructor) will raise the SelectedIndexChanged event, and therefore cause the code in your event handlers to be executed. If you set the selected index to 1, variableA will be set to 0. If you set the selected index to 2, variableA will be set to 1. Or whatever logic your code in the event handler method implements.

Of course, the SelectedIndexChanged event is only raised when the selected index is changed. If you set the selected item to "item1" in the constructor, and then the user re-selects "item1", the event won't be fired again. But that's probably what you want. The value of variableA wouldn't change anyway by your current logic.

OTHER TIPS

yes, variableA=0 will be the value.

I am not illustrating this anymore. Cody Gray's explanation is great!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top