2008-08-30 12 views
1

如何將方法輸出分配給沒有代碼背後的文本框值?如何將方法的輸出分配給無背後代碼的文本框值

<%@ Page Language="VB" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<script runat="server"> 
    Public TextFromString As String = "test text test text" 
    Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w") 

    Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer) 
     Return New String(Input, Count) 
    End Function 
</script> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title>Test Page</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <%=TextFromString%> 
     <br /> 
     <asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox> 
     <br /> 
     <%=TextFromMethod%> 
     <br /> 
     <asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>   
    </div> 
    </form> 
</body> 
</html> 

它主要是這樣設計師們可以在aspx頁面中使用它。看起來像一個簡單的事情,把一個變量值轉換成一個文本框給我。

它也困惑於我爲什麼

<asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label> 

<asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox> 

的作品,但

<asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox> 

導致編譯錯誤。

回答

2

.ASPX文件中有幾種不同的表達式類型。有:

<%= TextFromMethod %> 

它只是保留一個文字控件,並在渲染時輸出文本。

,然後有:

<%# TextFromMethod %> 

這是一個數據綁定表達式,當控制是數據綁定評價()。還有表達式生成器,如:

<%$ ConnectionStrings:Database %> 

但在這裏,這不是真正重要的....

所以,<%= %>方法是行不通的,因爲它會嘗試插入文字到.text屬性......顯然,不是你想要的。

<%# %>方法不起作用,因爲TextBox不是DataBound,也不是它的父母。如果你的TextBox在Repeater或者GridView中,那麼這個方法就可以工作。

那麼 - 該怎麼辦?請撥打電話TextBox.DataBind()。或者,如果您的控制器超過1個,請致電Page_Load撥打Page.DataBind()

Private Function Page_Load(sender as Object, e as EventArgs) 
    If Not IsPostback Then 
     Me.DataBind() 
    End If 
End Function 
1

您是否嘗試過使用HTML控件而不是服務器控件?它是否也會導致編譯錯誤?

<input type="text" id="TextBox4" runat="server" value="<%=TextFromString%>" /> 
相關問題