2012-08-15 29 views
1

我想循環通過包含文本框和下拉列表的頁面上的控件並清除它們。vb.net循環通過控件不起作用

當我調試時,parent是當前頁面,值等於ASP.nameOfCurrentpage_aspx和 Type等於system.web.ui.page,但c的值爲ASP.site_master和system.web的類型.ui.control。我還將x放在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 
+0

@Taylor,感謝編輯我的帖子 – Kevin 2012-08-16 15:37:45

回答

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 
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 
+1

!= NULL在VB語法是 「狀態並沒有沒有」 或 「不c.controls是Nothing」 – N0Alias 2012-08-16 00:29:58

1

HTMLForm控件可能是嵌套的,可能在MasterPage下。或者使用函數完全遞歸,或者在If語句中添加一個查找主頁面的子句。這是斷點和Watch Window是黃金的地方。

例:

ElseIf c.GetType.ToString = "ASP.MasterPageName_Master" Then 
    ClearForm(c)