ASP.NET dynamically adding UserControl to PlaceHolder, not fire Click Event, only Page_Load

余生长醉 提交于 2019-12-02 04:01:20

If you fire *myButton_ServerClick* event, postback is invoked and ASP.Net want to fire called event, but your control is not added to the page, that's why ASP.Net ignore this event.

After postback and before event to be fired, you must add your control again and after them, event will be invoked.

Update

Something like this

Page:

<asp:Button runat="server" ID="btnTest" Text="Add control" OnClick="btnTest_Click"/>
<asp:Label runat="server" ID="result"></asp:Label>
<asp:HiddenField runat="server" ID="controlLoaded"/>
<asp:PlaceHolder runat="server" ID="phTest"></asp:PlaceHolder>

Code behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (controlLoaded.Value == "1")
        {
            AddControl();
        }
    }

    protected void btnTest_Click(object sender, EventArgs e)
    {
        AddControl();
    }

    protected void myButton_ServerClick(object sender, EventArgs e)
    {
        result.Text = "OK";
    }

    public object getControl()
    {
        var ph = new PlaceHolder();

        var exportInbBtn = new Button();
        exportInbBtn.Text = "Export Inventury";
        exportInbBtn.Click += new EventHandler(myButton_ServerClick);
        ph.Controls.Add(exportInbBtn);
        exportInbBtn.ID = "exportInbBtn";

        return ph;
    }

    private void AddControl()
    {
        var actualObject = (PlaceHolder)getControl();
        phTest.Controls.Add(actualObject);
        controlLoaded.Value = "1";
    }

Please note that UserControls are added by the below method - // First create the instance of user control var control = Page.LoadControl("~/folder1/UserControl1.ascx")

// Now add this control to placeholder as - placeHolder1.Controls.Add(control);

I hope this helps.

page.aspx

<asp:PlaceHolder ID="PlaceHolder1" runat="server" ></asp:PlaceHolder>

page.aspx.vb

Private Sub CreateControl()
    Dim vw As Control
    vw = CType(LoadControl("~/View01.ascx"), View01)
    vw.ID = "View_Dyn"
    PlaceHolder1.Controls.Clear()
    PlaceHolder1.Controls.Add(vw)
End Sub

Recreate it every postback

Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
    CreateControl()
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!