How to add user control at runtime in ASP.NET?

How to add a dynamic user control on a page in ASP.NET?

I have a div with ID="contentData" and several controls

  • one.ascx
  • two.ascx
  • three.ascx

Now I created the default.aspx page, which can receive parameters in the query string in one of the following ways:

 default.aspx?val=one default.aspx?val=two default.aspx?val=three 

I take the value from

 Request.QueryString["val"] 

Now, how can I load a specific control?

 <div ID="controlData"></div> 
+4
source share
4 answers

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 code block use Page.LoadControl to exit and get your user control, and then add it to your div using div Controls. Add

+14
source
 // Load the User Control Control uc = LoadControl("~/MyUserControl.ascx"); // Add the User Control to the Controls collection Page.Controls.Add(uc); 

for more information, follow this link - Extensive verification of user controls http://msdn.microsoft.com/en-us/library/ms972975.aspx

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

+3
source

Use the LoadControl programmatic method to do this programmatically:

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

Also, if you intend to add it to the div, make sure you make this div the managing server by adding runat = "server" in the markup

+1
source

I do not understand a little what you are asking, so forgive me if this does not answer the question.

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

If the number of possibilities is very large or dynamic, so that you don’t even know what the possibilities are during coding, you can put a wrapper, say div, and add elements to the β€œcontrol” property. But I would avoid this, if at all possible, because it would be very difficult to maintain: future programmers do not even know what controls can be on the screen.

0
source

Source: https://habr.com/ru/post/1393837/


All Articles