非使用FindControl方法找到深层嵌套的控件

首先看下示意图

 

上图中,有七层MasterPage嵌套,最后一层MasterPage有一个ASPX网页,在ASPX网页上有一个ASCX用户控件,在ASCX用户控件有一个TextBox控件。

在第一层的MasterPage拉一个Button和一个Label控件。 如今想按一下这个铵钮,去获取TextBox的值。

本只是一个实例,实际开发时,控件嵌套层数是一个未知数,最后一个也未必是TextBox。

 

 下面是Insus.NET解决方法。

由于层次是未知数,所以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,这个接口内有一个返回对象函数。

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在将来的程序中为变为什么控件,或是什么对象,也不知道它的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

 

posted @ 2012-09-27 12:02  Insus.NET  阅读(1310)  评论(0编辑  收藏  举报