[英]How to bind a classes property to a TextBox?
我有一個帶有字符串屬性注釋的Customer類,並且我試圖像這樣綁定它:
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text=<%=customer.Comments %>>
</asp:TextBox>
但是,它給了我錯誤:
服務器標記不能包含<%...%>構造。
我在類中也有一個名為GetCreatedDate的方法,在aspx頁面中,我正在做<%= GetCreatedDate()%>和<%GetCreatedDate();%>。 有什么區別?
或者,您可以在文件后面的代碼的Page_Load事件中設置值:
txtComments.Text = customer.Comments;
您應該使用“ <%#%>”進行數據綁定
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text="<%# customer.Comments %>">
</asp:TextBox>
試試這個吧。
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text=<%# customer.Comments %>>
</asp:TextBox>
注意=到#
使用如下所述的DataBinding語法<%#customer.Comments%>。 僅當TextBox是數據綁定的時,才評估此語法。 您通常會在DataBound列表中使用它。 在這種情況下,您需要手動對控件進行數據綁定。 重寫頁面的OnDataBinding方法並調用txtComments.DataBind();。
數據綁定語法是從aspx頁面以聲明方式設置ServerControl屬性的唯一方法。 其他語法的Response.Write發生在無法訪問ServerControl屬性的時間。 如果控件不在數據綁定控件內,則必須對其進行數據綁定。
如果您希望在頁面中使用所有聲明式內容,那么使用此方法將無濟於事,因為您仍然需要在后面的代碼中編寫代碼。
如果您想在沒有父DataBound控件的情況下單獨使用TextBox,則可以替代該TextBox的子類,添加一個AutoBind屬性,如果為true,則在該子類控件中調用其DataBind方法。 這樣,您就可以綁定值,而無需在后面的代碼中編寫數據綁定代碼。
您還可以將TextBox和其他表單控件添加到FormView控件並將其綁定到您的對象。 在這種情況下,您仍然可以使用DataBinding語法。
嘗試這個
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text='<%# customer.Comments %>'>
</asp:TextBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.