Easily Raise Events From ASP.NET ASCX User Controls

Say what you will about User Controls (ASCX controls) versus WebControls (classes inheriting from System.Web.UI.WebControl) but the simple fact is that often a User Control is the easiest and best way to design a piece of re-usable functionality in ASP.NET.  An essential component to re-use is encapsulation.  Without encapsulation of the inner-workings of a class, you're liable to have serious problems when it comes to maintenance and ease of re-use.  For anything but the simplest of components,  you're component is going to need to notify it's container by raising events.  So, if you're going to create re-usable ASP.NET UserControls, you're going to need to know how to create and consume events.

Unfortunately, many ASP.NET developers don't implement events from their user controls.  I think there's one big reason for this, and the problem lies in the Visual Studio IDE.  Visual studio does not automatically add a protected member variable for UserControls that are dropped onto and ASCX or ASPX control.  I have no idea why this was left out of the IDE, but I have a suspicion that it's led to developers not properly encapsulating their User Controls.  Since there's no automatic member variable, often controls are not thought of as components, like any other control on a web form.

Fortunately, there's a real easy way to solve this.  Say you drop a UserControl called MyControl.ascx onto another user control.  If this is the first control of this type dropped onto this control the control will be named MyControl1 in the HTML source.  The key to accessing events and other properties of this control is to add a member variable.  To add a member variable to the container class, you can simply add the line (C#):

protected  MyControl MyControl1;

… to the top of your container control's code behind.  Okay, so what does this do for us?  Well, now, we've got a control that we can communicate with, without doing Page.FindControl.  More importantly, we can easily wire up events that are raised in the child control and handle them in our parent!   Now, we're able to encapsulate the inner-workings of the child control and notify the parent when something interesting happens.

So, very quickly, there are two essential methods to have a handle on for raising events.   First, if you just need to notify the parent control that something happened, use standard System.EventHandler. This is cake. Simply define your event as a public member, like so:

public event System.EventHandler TabClicked;

Raise it whenever you want like this:

// Raise the tabclicked event.
if(this.TabClicked != null)
this.TabClicked(this, new EventArgs());

Then in your containing class you wire up the event like so:

this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

Where MyControl_TabClicked is a method with a signature that looks like this:

private void MyControl_TabClicked(object sender, EventArgs e){}

Simple!  Even cooler, if you type “this.MyControl.TabClicked +=” in the IDE, an press TAB twice, VS will wire up the event handler and create your method for you!Now, say you wanted to pass some specific data to the container control.  One way is to use a delegate. This comes in really handy, and is in fact quite easy too. For example, what if you wanted to pass some private value from the encapsulated child class? First create a custom class deriving from System.EventArgs with a member variable that contains your interesting private value:

public class TabClickEventArgs : EventArgs

   private String myString;
public String MyString
get { return myString; }
set { myString  = value; }

Then create a delegate for your event like so:

public delegate void TabClickEventHandler(object sender, TabClickEventArgs e);

The rest is just like before, except that you define your custom event hander, instead of the basic System.EventHandler.

public event TabClickEventHandler TabClicked;

And raise it like so.

// Raise the tabclicked event.
if(this.TabClicked != null

    TabClickEventArgs e = new TabClickEventArgs();
    e.SomeString = “test“;

this.TabClicked(this, e);

Finally, when you wire the event up, your method signature for the handler, just needs to match the signature of your delegate:

private void MyControl_TabClicked(object sender, TabClickEventArgs e) {}

This stuff is so easy and essential, that I can say with certainly that if you're doing ASP.NET development, and not raising events from your UserControls, you're probably not getting the maximum reuse out of your controls.


About Brendan Tompkins

Brendan runs CodeBetter.Com. He was twice awarded MVP for Microsoft .NET, and is a founder and the CTO of Quick180.Com More about Brendan at https://www.linkedin.com/codebetter
This entry was posted in ASP.NET Tutorials, Most Popular. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Sam Samnah

    lol omg nice bool? Does it persist true through postback?

  • Sam Samnah

    I’ve created a custom control with a custom listener based on HtmlAnchor objects href attribute. Therefore, I’ve had to wire up the href attribute with Page.ClientScript.GetPostBackClientHyperlink(this,[My custom event args]));

    now I’ve also typed out a delegate that handles my custom eventargs(called “DayViewEventArgs”) then created an event called DateLinkClicked, then I typed out a method to listen for the event called OnDateLinkClicked which checks for subscribers and performs some action based on whatever ctrl is subscribing to the event… I’ve also used RaisePostBackEvent to listen for the event as this is a web form. … Now my problem, I keep getting the error ”
    The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.” Do I also use onbubble or raisebubble… OR am I missing something? If you can please help me with this. I’m pulling out my hair and I don’t have much more to pull. lol

  • kaye

    very nice article specially for newbie like me. im trying to use this for my project, but im getting an error in
    this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

    “public event TabClicked is an event and cannot be called directly. Use a RaiseEvent statement to raise an event”
    why is that? i put it in OnInit of the aspx page (as what others recommended). i just thought you need to know that my project has nested ascx, and the event that i was trying to raise is inside the second ascx page. Meaning, aspx then ascx1 then ascx2 (ascx2 inside ascx1 which is in aspx). i hope you could help me. thanks.

  • kaye

    hi. this helps me alot understanding on how i will apply it to my code coz im new to asp.net. im kind of confuse in letter f though, i already have the Sub in ascx (button_click), what will i put in this Sub? i hope you could still take some time to answer my question. thanks a lot.

  • Cesar Rodezno

    You saved my life, I had many days to implement what you very well explain.

  • http://www.facebook.com/cguevara.aguilar Carlos Guevara

    Gracias! saludos desde México.

  • Ing_eneida

    Good Job Man! Thank’s a lot.

  • Burak Tarhanlı

    Thank you so much.

  • Almoujtahed

    Thanx, simple explanation!!!

    but can you also include the source code

  • farid bekran

    thank you .

  • Guest

     The delegate is used in this example to pass information from the user control to the parent which you have pointed correctly as this can be achieve by public properties, but delegates it can also be used to pass information from the parent to the control which is is great as your custom event can contain all the required information.

  • Aasdasd


  • Dr. No

    this.ignoreIndoctrinatingShitheads = true;

  • Asdasd

    Thanks .. 

  • Holly

    Awesome. Thanks alot. Nice writing style.

  • Guest

    fuck you

  • Murali0808

    it is very nice ..
    But can please tell me how raise a commandEventArg from Usercontrol

  • http://www.facebook.com/people/Wenshuo-Han/100000017393232 Wenshuo Han

    It is a great post !  Thanks,mate.

  • Croninrl

    Awesome article Brendan! I agree with everyone who said they’ve never ready anything that so simply describes eventing between pages and user controls. Thanks for posting!

  • http://www.facebook.com/people/Omar-Shaker/100001461858153 Omar Shaker

    Very helpful article 

  • http://pulse.yahoo.com/_OBIXF7SEXRUGK4HWJN3UWN77FE Omar Shaker

    Great article

  • http://www.orthodoxphotos.com/history.shtml Orthodox

    Thank you for this information brother!

    As a thank, I want to give you this spiritual gift:

    How old is the Orthodox Faith?

    If you are a Lutheran, your religion was founded by Martin Luther, an ex-monk of the Catholic Church, in the year 1517. If you belong to the Church of England, your religion was founded by King Henry VIII in the year 1534 because the Pope would not grant him a divorce with the right to re-marry. If you are a Presbyterian, your religion was founded by John Knox in Scotland in the year 1560. If you are a Congregationalist, your religion was originated by Robert Brown in Holland in 1582. If you are Protestant Episcopalian, your religion was an offshoot of the Church of England, founded by Samuel Senbury in the American colonies in the 17th century. If you are a Baptist, you owe the tenets of your religion to John Smyth, who launched it in Amsterdam in 1606. If you are of the Dutch Reformed Church, you recognize Michelis Jones as founder because he originated your religion in New York in 1628. If you are a Methodist, your religion was founded by John and Charles Wesley in England in 1774. If you are a Mormon (Latter Day Saints), Joseph Smith started your religion in Palmyra, New York, in 1829. If you worship with the Salvation Army, your sect began with William Booth in London in 1865. If you are Christian Scientist, you look to 1879 as the year in which your religion was born and to Mary Baker Eddy as its founder.

    If you belong to one of the religious organizations known as “Church of the Nazarene, Pentecostal Gospel,” “Holiness Church,” or “Jehovah’s Witnesses,” your religion is one of the hundreds of new sects founded by men within the past hundred years.

    If you are Roman Catholic, your church shared the same rich apostolic and doctrinal heritage as the Orthodox Church for the first thousand years of its history, since during the first millennium they were one and the same Church. Lamentably, in 1054, the Pope of Rome broke away from the other four Apostolic Patriarchates (which include Constantinople, Alexandria, Antioch and Jerusalem), by tampering with the Original Creed of the Church, and considering himself to be infallible. Thus your church is 1,000 years old.

    If you are Orthodox Christian, your religion was founded in the year 33 by Jesus Christ, the Son of God. It has not changed since that time. Our church is now almost 2,000 years old. And it is for this reason, that Orthodoxy, the Church of the Apostles and the Fathers is considered the true “one Holy Catholic and Apostolic Church.” This is the greatest legacy that we can pass on to the young people of the new millennium.

  • Gete


  • sangram

    I am trying to add web-user control dynamically,ya they get added when time to fire event they shy away.

    ShippingAddressControl.ascs.cs is as follows

    public partial class UserPages_ShippingAddress : System.Web.UI.UserControl
    // Delegate declaration
    //public delegate void OnAddMoreClick(object sender, EventArgs e);
    //public delegate void OnRemoveThisClick(object sender, EventArgs e);

    // Event declaration
    //public event OnAddMoreClick AddMoreClickHandler;
    //public event OnRemoveThisClick RemoveThisClickHandler;

    public event System.EventHandler AddMoreClicked;
    public event System.EventHandler RemoveThisClicked;
    protected void lnkBtnAddMore_Click(object sender, EventArgs e)
    // Raise the AddMoreClicked event.
    //if (this.AddMoreClickHandler != null) AddMoreClickHandler(this, e);
    if (this.AddMoreClicked != null) this.AddMoreClicked(this, new EventArgs());
    protected void lnkBtnRemoveThis_Click(object sender, EventArgs e)
    // Raise the RemoveThisClicked event.
    //if (this.RemoveThisClickHandler != null) RemoveThisClickHandler(this, e);
    if (this.RemoveThisClicked != null) this.RemoveThisClicked(this, new EventArgs());

    in my aspx.cs handlers are

    protected void ShippingAddressControl_AddMoreClickHandler(object sender, EventArgs e)
    /*reading total live control*/
    int TotalLiveShippingControl = int.Parse(ViewState[“TotalLiveShippingControl”].ToString());
    TotalLiveShippingControl = TotalLiveShippingControl + 1;

    /*add one more control*/
    Control ControlObj = LoadControl(“ShippingAddressControl.ascx”);
    ControlObj.ID = “ShippingAddressControl” + TotalLiveShippingControl.ToString();

    /*increase counter of total live control*/
    ViewState[“TotalLiveShippingControl”] = TotalLiveShippingControl;
    protected void ShippingAddressControl_RemoveThisClickHandler(object sender, EventArgs e)
    /*remove current control*/
    Control ControlObj = (Control)sender;

    /*decrease counter of total live control*/
    int TotalLiveShippingControl = int.Parse(ViewState[“TotalLiveShippingControl”].ToString());
    TotalLiveShippingControl = TotalLiveShippingControl – 1;
    ViewState[“TotalLiveShippingControl”] = TotalLiveShippingControl;

    To wireUp using these two functions

    public void AddEventHandler(UserPages_ShippingAddress ShippingAddressControl)
    ShippingAddressControl.AddMoreClicked += new EventHandler(ShippingAddressControl_AddMoreClickHandler);
    ShippingAddressControl.RemoveThisClicked += new EventHandler(ShippingAddressControl_RemoveThisClickHandler);


    public void UserControlEventWireUp()
    int TotalLiveShippingControl = int.Parse(ViewState[“TotalLiveShippingControl”].ToString());
    string StrControlName = string.Empty;
    UserPages_ShippingAddress[] UserPages_ShippingAddressObjArr = new UserPages_ShippingAddress[TotalLiveShippingControl];
    int j = 0;
    for (int i = 0; i < TotalLiveShippingControl; i++)
    j = i + 1;
    StrControlName = “ShippingAddressControl” + j.ToString();
    Control cc = Page.FindControl(StrControlName);
    UserPages_ShippingAddressObjArr[i] = (UserPages_ShippingAddress)cc;

    if (UserPages_ShippingAddressObjArr[i] != null)

    can anyone help me out?

  • http://none Ujjal

    This is really a good article. Helped implementing the User Controls events. Thanks Brendan

  • gabi

    Hi Brendan great article

    however I do have one question, when i use the delegate the following line does not apply anymore, what to do to make it fit?

    this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

  • Kriya

    Hi great article Brendan

    I do however have one question, when you use the delegate the following line does not apply anymore. What to do with it?

    this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

  • Ivan

    Good Brain on you. Clear & Concise.

  • aditya

    Really A good post

  • jaksitra

    Hi… just curious… you have a public property called “MyString” … but then later use this class and assign the property “e.SomeString.” …small detail, but shouldn’t that be “e.MyString?” …or am I incorrect?

    public class TabClickEventArgs : EventArgs
    private String myString;
    public String MyString

    if(this.TabClicked != null)
    TabClickEventArgs e = new TabClickEventArgs();
    e.SomeString = “test“;
    this.TabClicked(this, e);


  • Gene

    Couldn’t be easier. Thanks for a concise and understandable explanation.

  • Eric Mamet

    Yesterday evening, I found the design solution to my problem and it was effectively to encapsulate the functionality of my User Control and raise special events.
    My little brain kept ticking in the background because I was not sure how to implement this and I (try to) make a rule of not working week-ends…
    This article is just simply brilliant!
    Just the answer I needed. I’ll be able to relax for the week-end now

  • a_n00b_us

    What if you are loading in a user control dynamically like I am. how do I wire up my events then?

    Dim Job_Details As UserControl = LoadControl(“~/JobDetails.ascx”)
    Job_Details.ID = “Job_Details1″

    AddHandler Job_Details.Results_LoadTab_JobDetails, AddressOf what goes here???????

    ‘parent control housing dynamically created control
    RaiseEvent Results_LoadTab_JobSeekerDetails(JobID)

    ‘this is in my usercontrol
    Public Sub Load_JobDetails(ByVal JobID As Long)
    ‘Do all the cool stuff here
    ‘but how do i call this?
    End Sub

  • Richard

    This is probably the only article that has ever explained this properly – Legendary!

  • Realist

    thank you!

  • Pablo

    Thank you for the write up. It’s nice to see it done so simple.

  • Griegs

    Tom Pester, you are a legend. Cheers dude. So glad I scrolled to the bottom to check for sample code. :)

  • Tom Pester

    You can also use another approach by overriding the accessors of the event :

    public event EventHandler onButSavClicked
    add { butSave.Click += value; }
    remove { butSave.Click -= value; }

    This saves some typing since you dont have to implement the event in the user control that just throws it again, don’t have to check for null and don’t have to add fe. Onclick event on the usercontrol.

  • James

    Thanks – this described just enough to get me started – now I’m going to apply this technique across my entire project (well, at least where it’s applicable). Thanks again!

  • Ian

    My thanks join the many others. Jsut to make it even easier for some, here is all you need to do in ASP.NET 2.0 with VB.net:

    in control:
    Public Event MyEvent As System.EventHandler

    (do this in whatever sub or func as needed)
    RaiseEvent MyEvent(Me, New EventArgs())

    and in container:
    Protected Sub MyControl_MyEvent (ByVal sender As Object, ByVal e As System.EventArgs) Handles MyControl.MyEvent
    ‘do something
    End Sub

  • Cenon Del Rosario

    I have been doing this before but have a question…

    How come I cannot do the event subscription from the code front (i.e. aspx) like what you can do with server controls?

    It would be nice if you can do TabClicked=”MyControl_TabClicked” in the aspx rather than code.

    BTW, I found a work around to this problem 😉

    Email: cenon@optusnet.com.au

  • Bhushan Deo

    Dear Sir,

    I want to fire the custom event from user control (c#) so , please if u have any sample code then send me it on this mail id deo_bhushan@yahoo.com

  • Parwej

    Thanx 4 saving lots of my time and showing me good way to use events in user control.

  • Leif

    Great article! Thanks for the straight forward explanation.

    In my case I used an event that was published from a User Control via a Master Page to a Page.

    – Leif

  • T8R

    Ok…I have a series of user controls which inherit from a base class that has an event defined in it. Each of these is sitting on a page (5 of them right now). When a change is made in a datagrid in any one of the user controls the page needs to respond. The user control raises the event but I can’t get the page to see the event. Likewise, there is an event that the page raises when a selection is made in a dropdown or two but I cannot get the user controls to see that page level event.

    How and where should these events be defined (I’m using VB.NET) so that UC’s and Page can see the others events and live happily ever after? Any ideas?

  • Mark

    You don’t need to declare the child control as ASP.NET does this for you when you include the control in the page – you will already have a local object called MyControl1 if you give it that id, eg:

    Then you can just use the public properties of your control when the event fires:

    private void MyControl1_EventFired(object sender, EventArgs e)
    //set the value of a text box as an example
    ATextBoxOnTheContainingPage.Text = MyControl1.PublicProperty;

  • stm

    Some explanation for Jino :) (only .net 2.0)

    We have an aspx page with a codebehind file.
    And we have a usercontrol: an ascx file with also a codebehind file.
    You drop your usercontrol to the aspx in design view or manually (I prefer this) add it in source view.

    a) MyControl1 is the id of the usercontrol in the asPx file.

    b) protected MyControl MyControl1; needs to move in the asPx’s codebehind. In WAP you doesn’t need this see the previous comment.

    c) public event System.EventHandler TabClicked; go to the asCx’s codebehind.

    if(this.TabClicked != null)
    this.TabClicked(this, new EventArgs());

    also could be in any function in asCx’s codebehind. This raises the event.
    (In fact by the .net event declaring “rules”, this should be called from a protected virtual function OnTabClicked( EventArgs e ) { … }, but doesn’t care about this now.)

    e) this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

    should be in the asPx’s codebehind that way:

    protected override void OnInit(EventArgs e)
    this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

    f) private void MyControl_TabClicked(object sender, EventArgs e){} should be in the asPx’s codebehind, this handles the usercontrol event.

    g) The rest of the article show you how to fine tune your event (sending additional info) in the usercontrol, by declaring a custom delegate.

    hope this helps.

  • stm

    Nice article, I’m using this since asp.net 1.1, but I’ve some comment for asp.net 2.0 / vs2005, maybe it helps.

    … “Visual studio does not automatically add a protected member variable for UserControls that are dropped onto and ASCX or ASPX control” …

    I think this is true only for the “web site” project model. In the wap (“web application project model”), we get the protected member automatically in the “aspx.designer.cs/aspx.designer.vb” partial class.
    With WAP:

    protected MyControl MyControl1;

    not needed in the code behind, because already declared in the partial class!

    But there is a small problem with this automation:
    What if my page is inherited from a base class and I want to declare MyControl1 in the base class? If I simply put the declaration in the base class, we could get warning CS0108! In that case we can delete the declaration in the designer file, and the IDE will not add declaration again (until the same declaration remains in the codebehind class, or in a base class).

    What do you think?

  • Jenssi

    Awesome! Incredibly simple and infinitely useful. Thanks for posting this!

  • Gopala

    Hi, I figured it out.
    Use OnInit method on your containingpage and initialize the user control and event there. Just like below
    protected override void OnInit(EventArgs e)
    mypager.ItemClicked += new ItemClickEventHandler(this.HandlePagerEvent);
    mypager.EnableViewState = true;

    The problem i faced before is on postback, the Properties of control were becoming null. so is the event and unable to raise it. OnInit takes care of this…..


  • Gopala

    i am unable to register the event. do i need to use InitializeComponent() to register the event below? (I am using vs2005)
    I used “this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked)” but
    the TabClicked always giving me null.

    am i doing anything wrong? anybody who experienced this please reply back.


  • Anil

    Hi Btompkins

    I will again reapeat what Jino has said, and will be thankfull and appreciate if you or somebody take some take time and explain it in more detail so that the newbie like me and others can also used this. Thanks in Advance


    ***********Jino said **********
    Jino said:
    Hi there,

    I have been looking for a solution to get my user control events fired. This blog has helped many people and I think it is gonna help me too. But I am a newbie and also I develop in Vb.net. Even though there is a translation in one of the posts, it didnt make things very clear to me. I understand the concept of creating the instance of the control in the parent control and transferring the handling of the event to the parent.

    The name of the control mentioned in the article above – ‘MyControl1′ – is this the ‘ID’ of the user control inside the

    tag of the Parent Control HTML ?

    Being a newbie, I couldnt figure out which parts of code goes where. There are too many places to put the code snippets in – User Control HTML, USer Control Code Behind, Parent Control HTML and Parent Control Code Behind. Can someone take the pain of explaining this article a little further so that I can also try this magic nd make my user control events work?

    I am sure a lot of newbies would appreciate this effort. I see the same questions raised in many other forums ending up in unsatisfactory or not so detailed answers.

    Thanks very much in advance. Someone please take the time. We are looking upto u guys for ur expertise.


  • tadhg88

    so simple and yet so effective this saved me a lot of reading/searching
    thanks alot brendan very much appreciated

  • btompkins

    Pritam, you are correct sir!

  • Pritam

    Article is too good.. Only the mistake is in wiring the event it should be

    this.MyControl1.TabClicked +=new EventHandler(MyControl_TabClicked);

    Thanks Brendan for nice article !

  • Dr Feet

    Awesome! Thank you.
    Saved at least a days work

  • btompkins


    You no longer need to do this with ASP.NET 2.0, in 1.1 this was necessary to get access to the instance of MyControl that was created by the runtime.

  • Jeff

    So you put the “protected MyControl MyControl1;” line in the page that you drug the user contron onto. Seems to me this merely declares a variable MyControl1 as type MyControl. This MyControl1 variable will be set to null.

    Normally to use a class you must instanciate it. So you would write the line “MyControl1 = new MyControl();”. If you do this, the reference that is shoved into variable MyControl1 is for an entirely new instance of the control (not the one you want. You want a reference to the user control that you drug onto your page.). How do you do this?


  • David Flamini

    Walt Sully: Can you explain how to solve the problem you comment above? Please! Regards!

  • FSulistio

    When I ran the code in debug mode why this line
    if(this.TabClicked != null) always evaluates to null (undefined value). So the event could not be raised. What did I miss?

  • Greg Park

    Write a book, you were the first person to explain this clearly.

  • StephK

    I was so glad to see this article posted. It was easy to follow and I thought that I was seeing the light at the end of the tunnel but then ran my app…I got the object not set to an instance error when declaring my control on my page’s code behind.

    I am inserting my control into a template column of a gridview. So there are x instances of this control on my page all with the same id. Does anyone have any ideas about how I could take the info from this article one step further and allow me to implement custom event handling on controls within a gridview?

  • Venerable Bede

    Very good article. Its amazing how few clear and concise articles there are out there.


  • Walt Sully

    More specifically

    if (this.TabClicked == null)

  • Walt Sully

    ERRATA – the if-test should be for equality. That is, if the EventHandler == null

  • http://sully.faculty.tcnj.edu/ Walt Sully

    An excellent article. No need to ask “where’s the beef?” For the poor soul out there, who ends up with the kiss of death
    “Object reference not set to an instance of an object”
    after doing everything Brendan outlined, well, in Visual Studio 2003 the code gen feature can clobbler lines you’ve entered manually. MS warns about diddling in this area and that’s too bad. The symptoms are — it works for awhile and then breaks, usually when the code gen needs to register a new handler automatically in the container class.


    // Raise the tabclicked event
    if(this.TabClicked != null) throw new Exception(“missing Event Handler registration in container class InitializeComponent() – Visual Studio may have removed it!”);

    this.TabClicked(this, new EventArgs());


  • Jino

    Hi there,

    I have been looking for a solution to get my user control events fired. This blog has helped many people and I think it is gonna help me too. But I am a newbie and also I develop in Vb.net. Even though there is a translation in one of the posts, it didnt make things very clear to me. I understand the concept of creating the instance of the control in the parent control and transferring the handling of the event to the parent.

    The name of the control mentioned in the article above – ‘MyControl1′ – is this the ‘ID’ of the user control inside the

    tag of the Parent Control HTML ?

    Being a newbie, I couldnt figure out which parts of code goes where. There are too many places to put the code snippets in – User Control HTML, USer Control Code Behind, Parent Control HTML and Parent Control Code Behind. Can someone take the pain of explaining this article a little further so that I can also try this magic nd make my user control events work?

    I am sure a lot of newbies would appreciate this effort. I see the same questions raised in many other forums ending up in unsatisfactory or not so detailed answers.

    Thanks very much in advance. Someone please take the time. We are looking upto u guys for ur expertise.


  • DS

    Got it. This article saved me big time!!

  • DS

    All my ASCX inherit from a base class (ControlBase) which inherits from UserControl.

    These controls are dynamically loaded into a place holder as such:

    ControlBase c = (ControlBase)Page.LoadControl(“~/Controls/” + _control);


    Having trouble implementing delegates / events without having to do:

    case “ControlA”:
    ControlBase item = (ControlA)LoadControl(“Controls/ControlA.ascx”);
    ((ControlA)item).MyControlEvent += new ControlA.MyControlEventHandler(this.DynamicControlEvent);

    Hope that makes sense.

  • BillH

    This article really turned on a lot of lightbulbs. I was trying to do a pretty complex project with session variables. This is way too easy and just in the nick of time. Thanks a bunch.


  • praveen

    It just saved my day. Million Thanks for posting this article

  • Nathalie

    merci !

  • http://blog.eriklane.com Erik Lane

    Great post…getting to this stuff now and it really does help with re-use.


  • Suni Karumathil

    The article is great , explained well. Thanks for that.

    Reply to Devin:

    Declare the control as "Protected ".

  • devin.goble@gmail.com

    I did everything just like was in the article (thanks for being one of the only places I could find that explains this in a clear and easy to understand way, by the way). The problem is that I get a runtime error that says that the "object reference is not set to an instance of an object." What did I miss? I tried to create a reference to the object. Then what happens is that I get an error that says: The type ‘System.Web.UI.UserControl’ has no event named ‘itemCommandEvent’. This is on the line that has the even wired up to the proper method. This seems so straight forward I must be screwing up somehow. Thanks for the article though 😀

  • Dev

    Everytime I change something in the front , the tabClick event gets removed from the Web Form Designer generated code.How to keep it there?

  • igor.dubrovinsky@gmail.com

    thanks for great post! however, my problem goes beyond containing a single instance of the child control. i have a placeholder which contains children in its Controls collection. The problem arises when i’m trying to do the following:

    a. maintain the state of the parent control

    b. raise events from children controls to the parent

    i assume the right way to approach this problem would be

    a. to store the child control(s) in the viewstate (in order to persist its state between roundtrips) and recreate it on every

    page_load event handler.


    b. iterate through the Controls collection of the parent’s control’s place holder object, dynamically identify its type, and only then, we’ll be able to "sign up" for events of the child controls…

    am i making any sense?

    gents, a good explanation or a link would be appreciated. be well!

    Igor Dubrovinsky

  • bill

    did you find out

  • Brendan Tompkins

    Make sure you add your control in the appropriate event, before the event is handled. You probably want to use the OnInit method, or CreateChildControls for this.

  • Adamz

    I am attempting to use this technique with dynamically loaded user control. I am not finding that the event is wired up correctly. Any thoughts?

  • John Terrill

    Thanks. That is very clear and helpful. But how do I keep the event handler for the user control active in the containing class when using OutputCache in the user control?

  • Max


    Thank you for the VB AddHandler translation !!!

  • Jamie Sanders

    Ditto to all the above really. Thanks for this article, it really helped me out especially after the msdn proved useless. Although being a VB programmer this line baffled me for ages:

    this.MyControl.TabClicked +=new EventHandler(MyControl_TabClicked);

    The equivalent in VB is:

    AddHandler Me.MyControl.TabClicked, AddressOf MyControl_TabClicked


  • Dan Poincelot

    Not a lot of info available on this in print, found a few articles online after an exhausting search. Thanks, this seems to work much better the OnBubbleEvent which was causing strange behavior for me.


  • samir

    awesome, saved my day. keep good articles coming!!!

  • Paul Meyer

    It’s easy now after your great explanation. Thanks for the write up.

  • Brendan Tompkins

    Yes, it’s simple! I really think the issue is getting a reference to the control in the first place. What got me thinking about this was that on DNR this week, Carl Franklin mentions using FindControl for this. If you’re doing FindControl, you’re probably not wiring up events.. Or at least if you are, you’re doing wayyy to much coding to get at it..

  • Mark Bonafe

    It just couldn’t be any simpler. I just take this stuff for granted. I never even thought about posting on it. Great post, though. I’m sure many developers could use the info.

    Thinking about it further, I’ll bet a number of developers don’t use their own events because it’s just a little "tricky" to implement. Your explanation of it is perfect. It really is easy to do.