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

本文介绍了一种在ASP.NET中跨多层MasterPage获取控件值的方法。通过实现一个通用接口并使用递归查找控件的方式,可以灵活地从任意深度的页面结构中获取指定控件的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看下示意图

 

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

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

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

 

 下面是Insus.NET解决方法。

由于层次是未知数,所以Insus.NET写一个迭代方法:

ExpandedBlockStart.gif 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,这个接口内有一个返回对象函数。

ExpandedBlockStart.gif 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用户控件实作这个接口:

ExpandedBlockStart.gif 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铵钮事件:

ExpandedBlockStart.gif 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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值