Ahmed
Ahmed

Reputation: 114

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

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

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

Now I have created a page default.aspx, which may get parameters in query string, in one of the following ways:

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

I am taking the value from

Request.QueryString["val"]

Now how do I load specific control in this?

<div ID="controlData"></div>

Upvotes: 6

Views: 17647

Answers (4)

aked
aked

Reputation: 5815

// 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

Upvotes: 3

Jeff Turner
Jeff Turner

Reputation: 1347

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

Upvotes: 17

Jay
Jay

Reputation: 27464

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.

Upvotes: 0

Icarus
Icarus

Reputation: 63956

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

Upvotes: 1

Related Questions