The @Reference Directive

When I want to add a user control to a page I use the @Register directive at the top of the page. and the I add the control to the markup. But what if I want to add a user control programmatically but I have no reference of it via the markup? That is where the @Reference directive comes to action.

What's the story?

We have a user control with the name myUserControl.aspx


We add at the top of the page the control we want to programmatically add like this...


And finally the controls is being added to the page like this...


In general, when we declare a control in the page layout we use @Register and when we create the control programmatically we use @Reference.

That's it ...

kick it on


  • It looks like you are using a web application project; In my experience, the @Reference is not needed for what you have shown.

  • If you try

    myUserControl m = new myUserControl();
    it won't work. Neither in a web application nor in a website project. More over in a web application you compile the above statement but the control won't be added to the page but in a website the above statement wont even compile if the Reference directive is not added.

    I am not sure if you mean that.

  • No, I believe he means that you can use LoadControl method without using the @Reference directive at all...

Comments have been disabled for this content.