2

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I'd also like to add that <%= (10 * 10).ToString() %> is a Response.Write((10 * 10).ToString());, just for better comprehension
This is odd. I tried your example: <asp:TextBox ID="TextBoxAmt" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "percent", "{0:###.##}") %>' Width='<%= (10 * 10).ToString() %>'/> But I get the error:Cannot create an object of type 'System.Web.UI.WebControls.Unit' from its string representation '<%= (10 * 10).ToString() %>' for the 'Width' property. (The TextBox is in a databound grid) I also tried a simple expression <%="40"%> and <%="40px"%>. Any idea what I'm doing wrong? Thank you.
@Ryan - Width is a Unit, so needs a number + a unit. My example should really be Width='<%= (10 * 10).ToString() %>px'
Hi @Oded, it still complained about not being a valid representation. I have boiled this down to the simplest form: <asp:Label runat="server" ID="tst" Text='<%="hi"%>' /> - this label doesn't display anything! (If I replace the expression with a literal, it displays). Thanks for your ongoing help.
@Ryan - just use <asp:Label runat="server" ID="tst"><%= "hi"%></asp:Label>
|
1

Beware of the type you bind to .

for instance

<asp:TextBox runat=server ID=C_TB_MyTB 
        Text=<%# MyText %> 
        Width=<%# MyWidth %>
    ></asp:TextBox>

Binding this textbox with

protected string MyWidth="300";
protected string MyText = "Bla bla bla...";

won't work , whereas :

protected int MyWidth=300;
protected string MyText = "Bla bla bla...";

will do...

good code to you,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.