Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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>
like image 375
Ahmed Avatar asked Jan 30 '12 19:01

Ahmed


People also ask

How user controls are loaded dynamically?

The user control dynamically loaded at runtime is strategically placed in a table cell in the ItemTemplate . This loading takes place in the method that handles the ItemDataBound event for each row of the Repeater .

What is user control how it is created?

User control is created in markup file with . ascx extension. We create two user control one for collect the user information and second for Display the user information. Step 1: Add the Web user control in your form with the name UserInformation.

What is the extension of user control file?

The file name extension for the user control is . ascx. Instead of an @ Page directive, the user control contains an @ Control directive that defines configuration and other properties.


3 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 codebehind use Page.LoadControl to go out and fetch your usercontrol and then add it to your div using the div's Controls.Add

like image 151
Jeff Turner Avatar answered Oct 26 '22 12:10

Jeff Turner


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

like image 36
aked Avatar answered Oct 26 '22 13:10

aked


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

like image 30
Icarus Avatar answered Oct 26 '22 13:10

Icarus