且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.net:动态加载web用户控件

更新时间:2023-12-06 09:48:46

请记住,每次你做一个回发时你与你的网页类的品牌新实例的工作。如果添加控件到您的网页类的previous实例的控件集合,你的需要重新添加它为每一个如下回发。

此外,如果你想的ViewState为控制恢复则需要前的Load事件添加到页面的。这意味着添加init或preINIT过程控制。

I have a asp.net web page with place holder control and Menu control when user select an item from the menu. It will dynamically load the control based on menu item's value.

I got the control loaded but if i click on the a link button or anything on the web user control (.ascx) The web user control (.ascx) will disappear. I do not know what is causing this. Can someone take a look at my code and see what i'm missing?

Protected Sub Menu1_Click(ByVal sender As Object, ByVal e As EventArgs)

    Select Case Me.Menu1.SelectedValue
        Case "CustMasterMain"
            Dim ccCustMasterMaint As UserControl = CType(Page.LoadControl("~/Controls/Franchise/CustMasterMaintControl.ascx"), UserControl)
            Me.phHolder1.Controls.Add(ccCustMasterMaint)
        Case "AcctRecInq"
            Dim ccAcctRecInq As UserControl = CType(Page.LoadControl("~/Controls/Franchise/custAccountsReceivableInquiry.ascx"), UserControl)
            Me.phHolder1.Controls.Add(ccAcctRecInq)
    End Select

End Sub

Remember that each time you do a postback you are working with a brand new instance of your page class. If you added the control to the controls collection of a previous instance of your page class, you need to add it again for every postback that follows.

Additionally, if you want ViewState to be restored for the control then it needs to be added to the page before the Load event. That means adding the control during Init or PreInit.