Search code examples
c#asp.netweb-controls

Use c# expression to define server tag property value


Is it possible to set the property of a server tag from a c# expression, i.e. something like

<asp:TextBox Width='<%= [some c# expression] %>'/> 

?

I though this would be pretty straightforward, but I can't get such an expression to run.

Thanks for any help

Ryan


Solution

  • Yes, this is possible. You need to make sure the control runs server side (runat="server"), but depends on exactly what you are trying to evaluate in the expression.

    So long as the expression returns a string, it should be fine.

    <asp:TextBox id="txt" runat="server" Width='<%= (10 * 10).ToString() %>px'/> 
    

    This will result in a width='100' in the browser.

    Update:

    The above is completely wrong. You cannot put server side code render blocks (<%%> and <%=%>) in a server side control markup in this manner (since it already is a run server side).

    In order to dynamically control the value, this needs to be done either in codebehind or within separate render blocks:

    <%
      txt.Width = (10 * 10).ToString() + "px";
    %>
    <asp:TextBox id="txt" runat="server" /> 
    

    See this and this for reference.