经常用到使用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