Take the 2-minute tour ×

I am struggling how to set a custom property which is suppose to point to an instance of my custom class on an ASP.NET webcontrol.

Sample web control:

public class CustomControl : System.Web.UI.WebControls.Panel
  public IFactory Factory { get; set; }

Code behind:

public partial class Main : System.Web.UI.Page
  public IFactory GetFactory { 
    get { return new CustomFactory(); } 

public class CustomFactory : IFactory {}

The custom factory get initialized on the code behind. In my markup (not in code behind), I need to set the Factory property on my CustomControl to the instance in my code behind. Any variation of inline code that I tried did not work:

<asp:CustomControl ID="MyCustomControl" Factory="<%GetFactory%>" runat="server" />
<asp:CustomControl ID="MyCustomControl" Factory="<%=GetFactory%>" runat="server" />

Can anyone assist how to do this?

share|improve this question
Why does it have to be in the markup? –  Dave Zych Oct 3 '12 at 18:32
To keep the code behind cleaner. –  BlueChameleon Oct 3 '12 at 18:37
I'm not sure that's good reasoning - by attempting to keep the code behind cleaner, you're mucking up the markup. I don't necessarily see how adding one line of code makes the code behind messy. –  Dave Zych Oct 3 '12 at 18:39
My line of thinking was that the user drops the control into the aspx and sets all its properties there and does not have to go to the code behind to do anything else. –  BlueChameleon Oct 3 '12 at 18:42
add comment

1 Answer

up vote 1 down vote accepted

You just can't assign it on the control tag markup, the tag markup is rendered as html and has no logic to do it that way, html won't interpret te result of GetFactory. What you can do is to set if on your markup, not it the control tag property, but inside code brackets just like this:

<%MyCustomControl.Factory = this.GetFactory;%>
share|improve this answer
I tried this, but on the OnInit of the custom control the Factory property is null. Does that code above execute on OnPreRender? –  BlueChameleon Oct 3 '12 at 18:43
Doesn't matter if Factory property is null, because you're setting its value to this.GetFactory. What might be null is the control. In order to better understand this, check out what happens on page lifecycle (see Render section) –  danielQ Oct 3 '12 at 18:51
What I was trying to say is that I can do what you suggested, but that assignment will happen after the OnPreRender event and that is way too late for me. –  BlueChameleon Oct 4 '12 at 13:36
add comment

Your Answer


