yael
yael

Reputation: 11

set one time property value of usercontrol with multiple instance

I have user control with multiple instances in page. In page.aspx function page_load I know if I want to visible or hide something in this control for all instance of this control. In my pages I have usercontrols that contain this usercontrol.

for each page there are another conditions to visible or hide something in this control - (property cant be static...)

I am looking for a right solution.. thanks!

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

Upvotes: 0

Views: 156

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460158

You could use this recursive extension method to find all references of this control:

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

Now its easy with 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
        }
    }
}

Upvotes: 1

Related Questions