Frage

I am trying to solve the following issue:

I have a user control that needs to be dynamically loaded inside another control. This dynamically loaded control raises an event and as per my knowledge the events raised by dynamically loaded control will only be handled correctly if the control is created and loaded during the onload event. There is one more constraint that i have to consider when loading the control dynamically and that is a property in parent control. This property will determine if the control should be loaded or not.

Pseudo Code:

ControlA
  Property ShowControl
  ControlA has a CheckBox(chkShowControlIfSelected)
  OnLoadEvent()
    If chkShowControlIfSelected.checked checked and ShowControlProperty is set
    {
       reate ControlB Dynamically
       ControlB.Event += EventHandler()
       Add ControlB to ControlCollection
    }

The problem i am running into is that if I include the code to load the controlB in prerender event then the property ShowControl is set correctly but the EventHandler() is not called. If I put the code to load the controlB dynamically in pageLoad event then property ShowControl is not yet set but in that case the eventHandler Code is called correctly.

Am i missing something or handling the code in incorrect event handlers?

War es hilfreich?

Lösung

Following is the working example:

ControlA:

public partial class ControlA : System.Web.UI.UserControl
{
    public bool ShowControl
    {
        get
        {
            if (this.ViewState["ShowControl"] == null)
                return false;
            else
                return (bool)this.ViewState["ShowControl"];
        }
        set
        {
            this.ViewState["ShowControl"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.ShowControl)
        {
            var controlB = (ControlB)this.LoadControl("ControlB.ascx");
            controlB.FileUploadingComplete += controlB_FileUploadingComplete;
            this.pnl1.Controls.Add(controlB);
        }
    }

    void controlB_FileUploadingComplete(object sender, EventArgs e)
    {
        //throw new NotImplementedException();
        Trace.Write("file upload completed");
    }
}

ControlB:

public partial class ControlB : System.Web.UI.UserControl
{
    public event EventHandler FileUploadingComplete;
    protected void OnFileUploadingComplete()
    {
        if (this.FileUploadingComplete != null)
            this.FileUploadingComplete(this, EventArgs.Empty);
    }

    protected void btn1_Click(object sender, EventArgs e)
    {
        this.OnFileUploadingComplete();
    }
}

Page (has ControlA present):

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.ControlA1.ShowControl = true;
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top