• 非使用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

  • 相关阅读:
    2018-2019-1 20165202 20165210 20165214 实验一 开发环境的熟悉
    20165214 朱文远 缓冲区溢出漏洞实验
    2018-2019-1 20165214 《信息安全系统设计基础》第三周学习总结
    2018-2019-1 20165214 《信息安全系统设计基础》第2周学习总结
    2018-2019-1 20165214 《信息安全系统设计基础》第1周学习总结
    20165214 2017-2018-2 《Java程序设计》课程总结
    编程实现类似Linux系统的cp功能
    编程实现Linux系统的od功能
    2017-2018-2 20165214 实验五《网络编程与安全》实验报告
    2018-2019-1 20165212 20165313 2016522 实验一 开发环境的熟悉
  • 原文地址:https://www.cnblogs.com/insus/p/2705388.html
Copyright © 2020-2023  润新知