非使用FindControl方法找到深层嵌套的控件
生活随笔
收集整理的這篇文章主要介紹了
非使用FindControl方法找到深层嵌套的控件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
首先看下示意圖
?
上圖中,有七層MasterPage嵌套,最后一層MasterPage有一個ASPX網頁,在ASPX網頁上有一個ASCX用戶控件,在ASCX用戶控件有一個TextBox控件。
在第一層的MasterPage拉一個Button和一個Label控件。 如今想按一下這個銨鈕,去獲取TextBox的值。
本只是一個實例,實際開發(fā)時,控件嵌套層數(shù)是一個未知數(shù),最后一個也未必是TextBox。
?
?下面是Insus.NET解決方法。
由于層次是未知數(shù),所以Insus.NET寫一個迭代方法:
IterationFindControl protected?Control?IterationFindControl(Control?control,?string?id)????{
????????if?(control.ID?==?id)
????????{
????????????return?control;
????????}
????????foreach?(Control?ctl?in?control.Controls)
????????{
????????????Control?c?=?IterationFindControl(ctl,?id);
????????????if?(c?!=?null)
????????????{
????????????????return?c;
????????????}
????????}
????????return?null;
????}?
?
為了獲取TextBox控件值,Insus.NET寫了一個接口Interface,這個接口內有一個返回對象函數(shù)。
IGetable using?System;using?System.Collections.Generic;
using?System.Linq;
using?System.Web;
///?<summary>
///?Summary?description?for?IGetable
///?</summary>
namespace?Insus.NET
{
????public?interface?IGetable
????{
????????object?GetObject();
????}
}
?
為什么要寫接口,因為Insus.NET不清楚這個TextBox在將來的程序中為變?yōu)槭裁纯丶?#xff0c;或是什么對象,也不知道它的ID是什么?
接下來,我們要為ASCX用戶控件實作這個接口:
View Code using?System;using?System.Collections.Generic;
using?System.Linq;
using?System.Web;
using?System.Web.UI;
using?System.Web.UI.WebControls;
using?Insus.NET;
public?partial?class?WebUserControl?:?System.Web.UI.UserControl,IGetable
{
????protected?void?Page_Load(object?sender,?EventArgs?e)
????{
????????
????}???
????public?object?GetObject()
????{
????????return?this.TextBox1.Text;
????}
}
?
最后是第一層MasterPage銨鈕事件:
View Code using?System;using?System.Collections.Generic;
using?System.Linq;
using?System.Web;
using?System.Web.UI;
using?System.Web.UI.WebControls;
using?Insus.NET;
public?partial?class?MasterPage?:?System.Web.UI.MasterPage
{
????protected?void?Page_Load(object?sender,?EventArgs?e)
????{
????}
????protected?void?ButtonGet_Click(object?sender,?EventArgs?e)
????{
????????IGetable?obj?=?(IGetable)IterationFindControl(this,?"WebUserControl1");
????????this.LabelResult.Text?=?obj.GetObject().ToString?();????????
????}
}
?
演示源程序(asp.net 4.5 + C#):
?http://download.cnblogs.com/insus/ASPDOTNET/Multiple_Nested.rar
?
總結
以上是生活随笔為你收集整理的非使用FindControl方法找到深层嵌套的控件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 桌面使用体验 远程访问win
- 下一篇: 开源云操作系统:找到适合自己的应用模式