简体   繁体   中英

How to bind a classes property to a TextBox?

I have a Customer class with a string property comments and I am trying to bind it like this:

<asp:TextBox ID="txtComments" 
             runat="server" 
             TextMode="MultiLine" Text=<%=customer.Comments %>>
</asp:TextBox>

However, it gives me the error:

Server tags cannot contain <% ... %> constructs.

I also have a method in the class called GetCreatedDate and in the aspx page, I am doing <%=GetCreatedDate()%> and <%GetCreatedDate();%>. What is the difference?

或者,您可以在文件后面的代码的Page_Load事件中设置值:

txtComments.Text = customer.Comments; 

you should use "<%# %>" for data binding

<asp:TextBox ID="txtComments" 
             runat="server" 
             TextMode="MultiLine" Text="<%# customer.Comments %>">
</asp:TextBox>

Try this instead.

<asp:TextBox ID="txtComments" 
         runat="server" 
         TextMode="MultiLine" Text=<%# customer.Comments %>>
</asp:TextBox>

Notice the = to #

Use the DataBinding syntax as stated, <%# customer.Comments %>. This syntax is only evaluated when the TextBox is databound. You would usually use it in a DataBound list. In this case you need to databind the control manually. Override the page's OnDataBinding method and call txtComments.DataBind();

The databinding syntax is the only way to declaratively set ServerControl properties from the aspx page. The Response.Write of the other syntax happens at a time that the ServerControl properties cannot be accessed. If the control is not inside a databound control, you have to databind it.

If you were looking to go all declarative in your page, you don't gain to much using this method because you still need to write code in the code behind.

An alternative if you want to use the TextBox on its own without a parent DataBound control would be to subclass the TextBox, add an AutoBind property, and in the subclassed control call its DataBind method if it is true. That would let you bind the values without writing databinding code in the code behind.

You could also add the TextBox and other form controls to a FormView control and bind it to your object. You can still use the DataBinding syntax in that case.

try this

<asp:TextBox ID="txtComments" 
         runat="server" 
         TextMode="MultiLine" Text='<%# customer.Comments %>'>
</asp:TextBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM