开发者

Load Server Control from Assembly and hook up events

I have several Server Controls, each in a separate assembly and I'd like to load one of them dynamically into a page depending on some choice. There seems to be a problem where the server side events in the control are not firing however.

e.g. Controls are of the form:

[ToolboxData("<{0}:MyPlugin runat=server></{0}:MyPlugin>")]
public class MyPlugin : WebControl, PluginSystem.Interface.IMyPlugins
{
    protected override void RenderContents(HtmlTextWriter output)
    {
        ...
        _btn = new Button();
        _btn.ID = "btnSave";
        this.Controls.Add(_btn);
        _btn.Click += new EventHandler(btn_Click);
        _btn.RenderControl(output);
    }
开发者_如何学Go    void btn_Click(object sender, EventArgs e)
    {
        //do something. This doesn't fire
    }
}

The controls are loaded from their assemblies:

    public static IMyPlugins GetPlugin(string assembly, string type)
    {
        var t = Type.GetType(type + ", " + assembly);
        IMyPlugins rtn = (IMyPlugins)Activator.CreateInstance(t);

        rtn.Initialise();

        return rtn;
    }

How do I inject the loaded assembly into a page so that the events in the control will fire? Is that possible?

Thanks for any help!


You're adding the controls way too late in the page lifecycle. Add the server side controls in the OnInit Page event is your best bet.

Check out this link for an overview of the lifecycle process. The controls need to be created by the time the postback event handling happens. This series is also really good.

Dynamically changing the page based on user choice can be a pain in the ass because of this. There are a few options to go with. The easiest way is to add all your controls in the OnInit and then remove them when you know the selection the user made.

If it's truly completely dynamic, and you have no idea what control you are going to render until after the postbacks have been handled, it can be easier to step away from ASP.NET's viewstate/postback system and check things yourself. You can always get the full range of post values at any time in the page lifecycle by checking the Form.Request collection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜