views:

443

answers:

2

I have a custom control that exposes a property. When I set it using a fixed value, everything works correctly. But if I try to set its value using the <%= %> tags, it goes a little whacky:

<cc:CustomControl ID="CustomControl" runat="server" Property1='<%= MyProperty %>' />
<%= MyProperty %>

When this gets rendered, the <%= MyProperty %> tag underneat the custom control is rendered as I expect (with the value of MyProperty). However, when I step into the Render function of the CustomControl, the value for Property1 is literally the string "<%= MyProperty %>" instead of the actual underlying value of MyProperty.

+1  A: 

Try <%# MyProperty %> in the CustomControl and see if that works.

cfeduke
+3  A: 

You control is initialized from the markup during OnInit. So if that syntax worked, it wouldn't have the effect you wanted anyway, since MyProperty would be evaluated during OnInit and not at render time (like it is with the second usage).

You want to use the data binding syntax instead:

<cc:CustomControl ID="CustomControl" runat="server" Property1='<%# MyProperty %>' />

Just make sure to call DataBind() on the container (Page, UserControl, etc).

Alternatively, you can set the property in your code behind:

CustomControl.Property1 = MyProperty;
Brannon
Is there no better answer to this? I use the <%= MyProperty %> syntax with MS controls all the time. Should not there be a way to do the same with custom controls.
Corey Downie
How are you using that syntax with MS controls?
Brannon