Search code examples
c#eventscomboboxselectedindexselectedindexchanged

Fire a comboBox SelectedIndexChanged event programmatically in C#


There is a comboBox and a button on a win form. How can I fire the comboBox selectedIndexChanged by clicking on the button.


Solution

  • You should rethink your code design a little. It seems you want to raise the event to trigger some action indirectly. Why not try it like this:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
         // do the things that should happen only if a real change happend
         // ...
         // then do the special thing you want
         DoTheOtherStuff();
    }
    private void button1_Clicked(object sender, EventArgs e)
    {
        // do the things to happen when the button is clicked
        // ...
        // then do the special thing you want
        DoTheOtherStuff();
    }
    private void DoTheOtherStuff()
    {
        // the special thing you want
    }
    

    EDIT: If your legacy code is so awkward as your comment suggests, you can still use this awkward way:

    private void button1_Clicked(object sender, EventArgs e)
    {
        comboBox1_SelectedIndexChanged(comboBox1, EventArgs.Empty);
    }