遍歷PlaceHolder中的web控件

經常用到使用PlaceHolder加載web用戶控件,遍歷控件取值就用到了。下面這個方法是遍歷所有控件,可以遍歷某一類控件(源碼是查找所有checkbox控件),遍歷所有類型控件,修改一下即可

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace SantGo.Bunli.Web
{
    public partial class Site1 : System.Web.UI.MasterPage
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if( !IsPostBack )
            {
                List<Control> checkBoxList = new List<Control>();
                FindSubControls( ContentPlaceHolder1, checkBoxList, new ControlMatchHander( CheckBoxMatchFunc ) );
                foreach ( CheckBox checkBox in checkBoxList )
                {
                    divDebug.InnerHtml += string.Format( "{0}, {1}<br />",
                        checkBox.ID,
                        checkBox.ClientID );
                }       
}
        }
        protected delegate bool ControlMatchHander( Control control );
        protected void FindSubControls( Control control, IList<Control> saveCollection, ControlMatchHander matchFunc )
        {
            if ( control.HasControls() )
            {
                foreach ( Control subControl in control.Controls )
                {
                    FindSubControls( subControl, saveCollection, matchFunc );
                }
            }
            else
            {
                if ( matchFunc( control ) )
                {
                    saveCollection.Add( control );
                }
            }
        }
        protected bool CheckBoxMatchFunc( Control control )
        {
            return control is CheckBox;
        }
    }
}


順便舉個例子說一下placeholder的用法。

第一步加載放置placeholder控件

<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>

第二步加載自定義web控件,記住這個加載一定要放到if (!IsPostBack)的外面,否在在回傳的時候 你講取不到placeholder中的控件

if (System.IO.File.Exists(Server.MapPath("test.ascx")))
    ph.Controls.Add(LoadControl("test.ascx"));

第三步,遍歷控件取值

//用上面的方法取控件,然後將取值
第四步over

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章