views:

143

answers:

3

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?

A: 

First off, give each of your textboxes their own ID. The ID is supposed to be unique across all elements on a page.

Then in the code behind (try your load event for your page to begin with) you'll want to put something like this:

myTxt.Text = MyNamespace.MyClass.StaticString

EDIT: You tried this yet?

<asp:TextBox ID="myTxt" runat="server"><% CodeBehind.FunctionOrProperty %></asp:TextBox>
Sonny Boy
If you notice in all my examples, the text boxes have IDs. Also, I am specifically trying to avoid setting this value in the code behind.
Kasey Speakman
The IDs need to be unique, not repeated as the same value in each textbox.
Sonny Boy
The second thing just offloads the assignment to the code-behind. The examples I gave above were tried separately (one text-box changed to look like each line before each subsequent try), not simultaneously.
Kasey Speakman
A: 

Try following.

<asp:TextBox ID="myTxt" runat="server"></asp:TextBox> <% myTxt.Text= " Whatever you want"  %>
Pragnesh Patel
Oddly, that doesn't work?! I tried that already as shown in the original question.
Kasey Speakman
+4  A: 

This is the best way to do it.

<asp:TextBox ID="myTxt" runat="server" Text='<%# MyNamespace.MyClass.StaticString %>' />

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).

Sam
Adding Page.DataBind() to the PageLoad event made the binding expression work in the .aspx page. I'm ok with adding Page.DataBind() to the code behind if this allows me to declaratively set control values. I was just trying to avoid setting single values in the code-behind.
Kasey Speakman