0

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.

2 Answers 2

0

If your uiComboBox is placed within the user control (named CustomControl), then you can wire up the handler in the constructor as follows:

uiComboBox.SelectedIndexChanged += uiComboBox_SelectedIndexChanged;

If on the other hand, the uiComboBox is placed outside the CustomControl, then you'd need to handle the event using the above technique and then manually invoke a method in the CustomControl.

public class MyForm:Form {
    MyForm(){
        uiComboBox.SelectedIndexChanged += uiComboBox_SelectedIndexChanged;
    }

    private void uiComboBox_SelectedIndexChanged(object sender, EventArgs e)       {
        customControl.InvokeSomeMethod(xxx);
    }
}
1
  • The CustomControl will need to have an event, which will effectively be triggered when the combox within the CustomControl (uiComboBox) uiComboBox.SelectedIndexChanged event occurs. I'm not too sure any of the solution provided above handle this? Oct 15, 2015 at 5:12
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.