How to assign a method's output to a textbox value without code behind

后端 未结 2 1592
忘了有多久
忘了有多久 2021-01-16 03:21

How do I assign a method\'s output to a textbox value without code behind?

<%@ Page Language=\"VB\" %>


        
2条回答
  •  青春惊慌失措
    2021-01-16 04:06

    There's a couple of different expression types in .ASPX files. There's:

    <%= TextFromMethod %>
    

    which simply reserves a literal control, and outputs the text at render time.

    and then there's:

    <%# TextFromMethod %>
    

    which is a databinding expression, evaluated when the control is DataBound(). There's also expression builders, like:

    <%$ ConnectionStrings:Database %>
    

    but that's not really important here....

    So, the <%= %> method won't work because it would try to insert a Literal into the .Text property...obviously, not what you want.

    The <%# %> method doesn't work because the TextBox isn't DataBound, nor are any of it's parents. If your TextBox was in a Repeater or GridView, then this method would work.

    So - what to do? Just call TextBox.DataBind() at some point. Or, if you have more than 1 control, just call Page.DataBind() in your Page_Load.

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

提交回复
热议问题