views:

113

answers:

1

Hi,

I have user control that inherits a base control class and these user controls are loaded using the LoadControl method, I can't seem to figure out how to raise events from user controls to the page that are dynamically loaded this way.

Thanks

Here is the delegate and event in the base user control class.


public delegate void SomeChangeEventHandler(object sender
, SomeChangeEventArgs e);

public event SomeChangeEventHandler SomeChangeEvent; 

public virtual void OnSomeChanged(SomeChangeEventArgs e)
{
    if (SomeChangeEvent != null)
    {
       SomeChangeEvent(this, e);
    }
}
+1  A: 

You can add event handlers manually like this:

MyUserControl myControl1 = (MyUserControl)LoadControl("ThisControl.ascx.cs");
myControl1.DataBinding += new System.EventHandler(this.MyControl_DataBinding);
Gabriel McAdams
I guess I don't understand what yor saying, I can add the event handler at the time I load the control?
OutOFTouch
I modified my answer to include an answer to your comment.
Gabriel McAdams
Please remember to accept this answer if you found it useful.
Gabriel McAdams
This is close but my event is in a control base class and the page can't see the method becuase the control is just a generic UserControl to the page therefore it can't see the custom event. Do I need to cast this to correct type first?
OutOFTouch
Yes. I modified my answer (slightly) to show a type other than UserControl.
Gabriel McAdams
Thanks for your help that would work if I was trying to add an event for built in event of a control class or a usercontrol class, but how do I get my page to see the customevent with out casting to the correct type of usercontrol I just loaded?
OutOFTouch
This is what my modified answer shows. You DO cast it to the type you are loading.
Gabriel McAdams
Sorry, I missed that. Thanks.
OutOFTouch
Sorry I am slow that means I should cast my user control to it's base type?
OutOFTouch
You should cast it to whatever object you need to, in order to access the event you need to handle.
Gabriel McAdams
Thanks man I finally got it to work, with your help.
OutOFTouch
No problem. I'm glad you got it working. Check out my new blog. I may be able to help in the future. http://www.thecodepage.com/
Gabriel McAdams