使用多个实例设置usercontrol的一次属性值

时间:2016-01-05 10:14:25

标签: c# asp.net user-controls

我在页面中有多个实例user control。 在page.aspx函数page_load中,我知道是否要在此控件中显示或隐藏此控件的所有实例。 在我的网页中,我usercontrols包含此usercontrol

对于每个页面,还有另一个条件可以在此控件中显示或隐藏某些内容 - (属性不能是静态的......)

我正在寻找合适的解决方案.. 谢谢!

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;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用此递归扩展方法查找此控件的所有引用:

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
        }
    }
}