I am trying to set a TextBox control’s Text property to the value of a variable declaratively. The only way I have found that will set the text property is if I place it in the code-behind page, which is what I’m trying to avoid.
I have tried to do all of the following, but with no success:
<asp:TextBox ID="myTxt" runat="server" Text='<%# MyNamespace.MyClass.StaticString %>' />
<asp:TextBox ID="myTxt" runat="server" Text='<%= MyNamespace.MyClass.StaticString %>' />
<asp:TextBox ID="myTxt" runat="server" Text='<% Response.Write(MyNamespace.MyClass.StaticString); %>' />
<asp:TextBox ID="myTxt" runat="server" /><% myTxt.Text = MyNamespace.MyClass.StaticString; %>
Is this even possible and if so how?
This is the best way to do it.
You said you tried it, but the trick is you have to call DataBind() on the page itself. <%# %> is a databinding expression and the value will be filled in when DataBind() is called.
You could call DataBind on the text box itself, but it’s better to call on the page to get everything (works recursively). You’ll want to be consistent and only call it on the page ’cause it’s possible that calling DataBind() multiple times on a control could have negative consequences (duplicate data in lists, etc).