zoukankan      html  css  js  c++  java
  • 非使用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

  • 相关阅读:
    mysql错误Error(1133): Can’t find any matching row in the use
    xtrbackup备份mysql
    配置Mysql审计
    Mysql:sql语句
    mysql基准测试与sysbench工具
    tomcat排错以及优化
    nginx反向代理
    Nginx
    服务器归分第一篇
    Android安装BusyBox(三星N7108)
  • 原文地址:https://www.cnblogs.com/insus/p/2705388.html
Copyright © 2011-2022 走看看