How to add user control on run time in ASP.NET?

后端 未结 4 1701
情话喂你
情话喂你 2021-01-18 23:55

How do I add a user control on page load dynamically in ASP.NET?

I have a div with ID=\"contentData\" and few controls

  • one.ascx
  • t
相关标签:
4条回答
  • 2021-01-19 00:31

    Use the Page's LoadControl method to do this programmatically:

    http://msdn.microsoft.com/en-us/library/t9ecy7tf.aspx

    Also, if your intention is to add it to the div, make sure you make that div a server control by adding runat="server" in the markup

    0 讨论(0)
  • 2021-01-19 00:38

    In your aspx

    <div id="div1" runat="server">
    
    </div>
    

    In Page_Load

        UserControl uc = (UserControl)Page.LoadControl("test.ascx");
        div1.Controls.Add(uc);
    

    All you need to do is make your div server bound by adding runat="server", and in the codebehind use Page.LoadControl to go out and fetch your usercontrol and then add it to your div using the div's Controls.Add

    0 讨论(0)
  • 2021-01-19 00:47
    // Load the User Control
    
    Control uc = LoadControl("~/MyUserControl.ascx");
    
    // Add the User Control to the Controls collection
    
    Page.Controls.Add(uc);
    

    for more details go thru this link - An Extensive Examination of User Controls http://msdn.microsoft.com/en-us/library/ms972975.aspx

    Also do read the use of ~ tidle in .net http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx

    0 讨论(0)
  • 2021-01-19 00:48

    I'm a little unclear what you're asking, so forgive me if this doesn't answer the question.

    Assuming the possible values are known in advance and that the number is modest -- like the three in your example -- the easiest thing to do is to include all the controls on the form with "visible=false", then in your Load method set visible to true on the one you want.

    If the number of possibilities is very large, or if it is dynamic so that you don't even know what the possibilities are at coding time, then you could put in a wrapper object, say a div, and add the items to its "controls" property. But I'd avoid this if at all possible because it would be very hard to maintain: future programmers won't even know what controls could possibly be on the screen.

    0 讨论(0)
提交回复
热议问题