How to Load User Control Programmatically
Sometimes it may happen that you need a functionality is not provided by built in ASP.net controls at that time developers can create ASP.net user controls or ASP.net custom controls.
- User controls. User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.
- Custom controls. A custom control is a class that you write that derives from Control or WebControl.
To load any user control programmatically you need to perform these two steps.
- Controls must be loaded
- Add the loaded control to control collection of loaded page.
For this i have created a usercontrol named as newcontrol
newcontrol Code
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="newcontrol.ascx.vb" Inherits="newcontrol" %> <asp:Label ID="Label1" runat="server" Text="How to Load User Control Programmatically, Demo"></asp:Label>
Now i am loading this user control to a new page at runtime
Partial Class usercontrol Inherits System.Web.UI.Page Protected Sub btnload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnload.Click Dim controltoload As Control Try controltoload = Me.LoadControl("~\newcontrol.ascx") Me.Controls.Add(controltoload) Catch ex As Exception End Try End Sub End Class
i found it very helpful, plz carry on.