我正在使用 ascx,我需要遍历所有控件并选择每个 cssClass 属性设置为“required”的控件。
我有以下代码:
foreach (Control masterControl in Page.Controls)
{
if (masterControl is MasterPage)
{
foreach (Control formControl in masterControl.Controls)
{
if (formControl is System.Web.UI.HtmlControls.HtmlForm)
{
foreach (Control contentControl in formControl.Controls)
{
if (contentControl is ContentPlaceHolder)
{
foreach (Control childControl in contentControl.Controls)
{
}
}
}
}
}
}
}
但是..我无法访问childControl.CssClass。我如何访问它?
提前致谢!
最佳答案
CssClass
属性是 WebControl class 的成员.
你必须检查该控件是否是一个Web控件,或者,如果它只是一个控件,你可以在属性集合中获取属性“class”。
例如,您可以这样做:
List<WebControl> wcs = new List<WebControl>();
GetControlList<WebControl>(Page.Controls, wcs)
foreach (WebControl childControl in wcs)
{
if(childControl.CssClass == "required") {
// process the control
}
}
您还必须递归迭代。代码在这里找到:Using C# to recursively get a collection of controls from a controlcollection :
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
foreach (Control control in controlCollection)
{
//if (control.GetType() == typeof(T))
if (control is T) // This is cleaner
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
关于asp.net - 遍历asp.net页面上的所有控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6422865/