Search code examples
c#.netcomboboxuser-controls

Call SelectedIndexChanged on ComboBox within User Control


I am using .NET 4 and trying to create a CustomControl but when I add this CustomControl onto my Windows Form, I want to have access to the SelectedIndexChanged for the ComboBox within my User Control.

Basically, what I want is when the Combo Box triggers the Selected IndexChanged, it will run some code within the Windows Form.

Below is what I have so far.

public partial class CustomControl : UserControl

...

private void uiComboBox_SelectedIndexChanged(object sender, EventArgs e)
{

}

What is the best way to do what I want?

Any help will be much appreciated.


Solution

  • In my CustomControl class, I had added in the following code so the SelectedIndexChanged on the combox will be picked up by my Custom Control when added as a Control onto a Form.

        public event EventHandler SelectedCBIndexChanged;
    
        ...
    
        public CustomControl()
        {
            InitializeComponent();
            this.uiComboBox.SelectedIndexChanged += new System.EventHandler(this.uiComboox_SelectedIndexChanged);
        }
    
    
        protected void uiComboox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SelectedCBIndexChanged != null)
                SelectedCBIndexChanged(sender, e);
        }
    

    Then on the Form, I add my Custom Control and Enable the SelectedCBIndexChanged property in the Designer which creates the event/method below which is what I was after.

        private void customControl_SelectedCBIndexChanged(object sender, EventArgs e)
        {
            // Do what I want
        }  
    

    I thought I'll leave this on here as it may help someone else in the future.