我在页面中有多个实例的user control
。在page.aspx
函数page_load
中,我知道是否要在该控件中为该控件的所有实例显示或隐藏某些内容。在我的页面中,我有包含此usercontrol
的usercontrols
。
对于每个页面,都有另一个条件来显示或隐藏该控件中的某些内容-(属性不能是静态的…)
我正在寻找一个正确的解决方案。。谢谢
ToPostFloorType floor = new ToPostFloorType();
UserControl uc;
DataTable floors;
floors = floor.FetchFloorTypesByPageID(pageID, iActiveVersion, iWithHeadAndFooter);
for (int i = 0; i < floors.Rows.Count; i++)
{
try
{
PlaceHolder phFloors = this.Page.FindControl("PlaceHolderFloors") as PlaceHolder;
uc = this.LoadControl("~" + floors.Rows[i]["FloorAscxPrefix"].ToString()) as UserControl;
uc.ID = floors.Rows[i]["PageTypeFloorTypeID"].ToString();
uc.EnableViewState = false;
phFloors.Controls.Add(uc);
}
catch (Exception ex)
{
throw;
}
}
您可以使用此递归扩展方法来查找此控件的所有引用:
public static IEnumerable<Control> GetControlsRecursively(this Control parent)
{
foreach (Control c in parent.Controls)
{
yield return c;
if (c.HasControls())
{
foreach (Control control in c.GetControlsRecursively())
{
yield return control;
}
}
}
}
现在使用Enumerable.OfType
:很容易
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
// presuming the type of your control is MyUserControl
var allUCs = this.GetControlsRecursively().OfType<MyUserControl>();
foreach (MyUserControl uc in allUCs)
{
// do something with it
}
}
}