1

我正在尝试循环浏览由文本框和下拉菜单组成的页面上的控件并清除它们。

我调试的时候,parent是当前页面,value等于ASP.nameOfCurrentpage_aspx,Type等于system.web.ui.page,但是c的值是ASP.site_master,type是system.web.ui.control。我还输入了 x 以查看它找到了多少控件,并且 x 返回为 1,即使页面上有 15 个左右的文本框。有没有办法可以强制 c 具有 ASP.nameOfCurrentpage_aspx 的值?或者这不是我的问题?任何帮助表示赞赏。

Protected Sub btnClear_Click(sender as Object, e as System.eventargs) Handles btnClear.Click
   ClearForm(Page)

End Sub

Public Sub ClearForm(ByRef Parent As Control)
    Dim c As Control
    Dim x As Integer = Parent.Controls.Count
    For Each c In Parent.Controls
        If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
            ClearForm(c)
        ElseIf c.GetType() Is GetType(TextBox) Then
            'is it a Text Box?
            Dim t As TextBox = c
            t.Text = ""
        ElseIf c.GetType() Is GetType(DropDownList) Then
            'is it a dropdown list?
            Dim d As DropDownList = c
            d.ClearSelection()
        End If
    Next

End Sub
4

3 回答 3

1

HTMLForm 控件可能是嵌套的,可能位于 MasterPage 下。要么完全递归你的函数,要么在 If 语句中添加一个子句来查找母版页。这是断点和观察窗口的黄金。

前任:

ElseIf c.GetType.ToString = "ASP.MasterPageName_Master" Then
   ClearForm(c)
于 2012-08-15T20:40:51.243 回答
1

谢谢大家的帮助。我没有尝试所有答案,但我将它们用于想法。这是我们在工作中提出的,它会找到并清除页面上的所有控件。我们必须找到链接到主站点 (cph) 的内容占位符。再次感谢所有建议。

Public Sub ClearForm(ByRef Parent As Control)
    Dim cph As System.Web.UI.WebControls.ContentPlaceHolder = Master.FindControl("MainBody")
    Dim c As Control
    Dim x As Integer = Parent.Controls.Count
    For Each c In cph.Controls
        If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
            ClearForm(c)
        ElseIf c.GetType() Is GetType(TextBox) Then
            'is it a Text Box?
            Dim t As TextBox = c
            t.Text = ""
        ElseIf c.GetType() Is GetType(DropDownList) Then
            'is it a dropdown list?
            Dim d As DropDownList = c
            d.ClearSelection()
        End If
    Next

End Sub
于 2012-08-16T15:36:08.300 回答
0

自从我用控件在 .NET 中编写任何东西已经有一段时间了,MVC 把我宠坏了,或者使用 VB.NET ......

但是我认为您可能需要通过控件堆栈递归:

Protected Sub btnClear_Click(sender as Object, e as System.eventargs) Handles btnClear.Click
   ClearForm(Page)

End Sub

Public Sub ClearForm(ByRef Parent As Control)
    Dim c As Control
    Dim x As Integer = Parent.Controls.Count
    For Each c In Parent.Controls
        If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
            ClearForm(c)
        ElseIf c.GetType() Is GetType(TextBox) Then
            'is it a Text Box?
            Dim t As TextBox = c
            t.Text = ""
        ElseIf c.GetType() Is GetType(DropDownList) Then
            'is it a dropdown list?
            Dim d As DropDownList = c
            d.ClearSelection()
        ElseIf c.Controls != null ' Does VB.NET support nulls? I forget
            ClearForm(c.Controls)
        End If
    Next

End Sub
于 2012-08-15T20:21:41.773 回答