常常用到使用PlaceHolder加載web用戶控件,遍歷控件取值就用到了。下面這個方法是遍歷全部控件,能夠遍歷某一類控件(源碼是查找全部checkbox控件),遍歷全部類型控件,修改一下便可web
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的用法。c#
第一步加載放置placeholder控件ide
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
第二步加載自定義web控件,記住這個加載必定要放到if (!IsPostBack)的外面,否在在回傳的時候 你講取不到placeholder中的控件。spa
if (System.IO.File.Exists(Server.MapPath("test.ascx"))) ph.Controls.Add(LoadControl("test.ascx"));
第三步,遍歷控件取值orm
//用上面的方法取控件,而後將取值第四步over