遍歷ASP.NET頁面控件
2024-07-10 12:57:32
供稿:網友
 
“如何遍歷asp.net頁面所有的控件呢?“,這是在社區發問的問題中最普遍的問題之一。通常我們對這個問題的回答為:”使用page類的controls 屬性來實現”!這個controls 屬性可以使我們獲取一個控件的所有子控件,但是如果其中的一個子控件同樣擁有自己的子控件,僅僅使用這個屬性便很難獲取asp.net頁面所有的控件。所以,要根本解決這個問題,我們需要書寫一些額外的方法以獲取頁面中的所有控件。
 假設頁面中有若干個textbox ,我們想遍歷整個頁面,然后獲取所有textbox的name和value ,并將它們顯示在datagrid中。
在我們開始遍歷頁面之前,需要建立一個類,用于存放那些textbox的name和value ,代碼如下:
public class utilityobj
private _name as string
 private _value as string
 public sub new(byval name as string, byval value as string)
 _name = name
 _value = value
 end sub 
 public property name() as string
 get
 return _name
 end get
 set(byval value as string)
 _name = name
 end set
 end property
 public property value() as string
get
 return (_value)
 end get
 set(byval value as string)
 _value = value
 end set
 end property
end class
 
 這個類包含兩個屬性:"name" 和 "value",再定義一個公有的arraylist(oarraylist),用于存儲數據。如圖:
 
 要實現遍歷asp.net頁面所有的控件,我們還需要定義一個主要的方法。這個方法接收一個control類型的參數,如果這個參數為textbox,則存儲它的 name 和 value。
 代碼如下:
public sub loopingcontrols(byval ocontrol as control)
 dim frmctrl as control
 oarraylist = new arraylist
 for each frmctrl in ocontrol.controls
 if typeof frmctrl is textbox then
 oarraylist.add(new utilityobj(frmctrl.id, directcast(frmctrl, textbox).text))
 end if
 if frmctrl.hascontrols then
 loopingcontrols(frmctrl)
 end if
 next
 end sub
 
 我們可以使用這個方法來實現遍歷asp.net頁面所有的控件
loopingcontrols(page)
 datagrid1.datasource = oarraylist
 datagrid1.databind()