亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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

標簽:
JavaScript

 

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

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

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

 

 下面是Insus.NET解决方法。

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

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

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

5acf071d0001405b00110016.jpgView 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铵钮事件:

5acf071d0001405b00110016.jpgView 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

 

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消