4

If I have a DropDownList control that makes up part of a CompositeControl how can I expose the SelectedIndexChanged event to the consuming aspx page?

Thanks

NikolaiDante
  • 18,469
  • 14
  • 77
  • 117

2 Answers2

11

There is a much simpler way that is a direct pass through.

Try this:

    public event EventHandler SelectedIndexChanged
    {
        add { this.TargetControl.SelectedIndexChanged += value; }
        remove { this.TargetControl.SelectedIndexChanged -= value; }
    }

[Edit] Unless of course you need to inject custom logic.

Brian Rudolph
  • 6,142
  • 2
  • 23
  • 19
  • I was using this method without success. My issue turned out to be a naming convention problem between my control property and my markup attribute. For others, remember that OnSelectedIndexChanged in markup will match to the SelectedIndexChanged property of your control. – cweston Nov 09 '10 at 15:10
4

Here's what you do. First declare an event like this:

public event EventHandler SelectedIndexChanged;

Then, internally, hook up to the DropDownList's SelectedIndexChangedEvent. In your event handler do something like this:

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.SelectedIndexChanged != null)
            {
                this.SelectedIndexChanged(sender, e);
            }
        }

All you're really doing is wrapping the original event and re-raising it.

EDIT: See Brian Rudolph's answer. That's in fact a much simple way of doing it.

BFree
  • 102,548
  • 21
  • 159
  • 201