【问题标题】:ASP.net webforms - accessing controlsASP.net webforms - 访问控件
【发布时间】:2018-08-29 11:50:19
【问题描述】:

我的问题是:

我的网页有点像这样:

     <asp:PlaceHolder ID="Formular" runat="server">
<table>
<tr runat="server" visible="true" id="1">
<td>  <asp:TextBox ID="TextBox13" runat="server" AutoPostBack="true" OnTextChanged="tb_Changed" CssClass="tx"></asp:TextBox>
</td>
</table>
    </asp:PlaceHolder>

现在我想循环浏览网页上的所有控件,但当然,我无法使用以下代码访问 TextBox13:

Dim tb as TextBox
For Each ctrl In Formular.Controls
            If TypeOf ctrl Is TextBox Then
                tb = ctrl
                If tb.Text.Trim.Length = 0 Then
                    tb.Style("background-color") = "red"
                    count += count + 1
                Else
                    tb.Style("background-color") = "white"
                End If
            End If
        Next

是否有任何优雅的简单方法可以访问该文本框?

我不使用 javascript 隐藏该表行的原因是因为此页面的代码稍后将在其他地方使用,并且不使用任何 javascript 会更容易。

【问题讨论】:

    标签: html asp.net vb.net webforms


    【解决方案1】:

    您可以通过以下方式访问文本框的对象:

    Dim szTextbox As String = Left(Request.Form("TextBox13"), 50) 获取内容为字符串

    TextBox13.Text 获取和设置文本框控件中的字符串

    更新

    基于找到特定的文本框。

    递归遍历页面,根据id查找文本框:

    Public Function FindControlRecursive(Of ItemType)(ByVal Ctrl As Object, ByVal id As String) As ItemType
         If String.Compare(Ctrl.ID, id, StringComparison.OrdinalIgnoreCase) = 0 AndAlso TypeOf Ctrl Is ItemType Then
              Return CType(Ctrl, ItemType)
         End If
    
         For Each c As Control In Ctrl.Controls
              Dim t As ItemType = FindControlRecursive(Of ItemType)(c, id)
    
              If t IsNot Nothing Then
                   Return t
              End If
         Next
    
         Return Nothing
    End Function
    

    代码来自:Looping through textboxes and labels

    【讨论】:

    • 谢谢,这是一种优雅而简单的方法……但没想到我在一页上有 10 种这样的情况,里面有很多文本框。
    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多