Link to home
Create AccountLog in
Avatar of cme0015
cme0015

asked on

Design time controls return nothing / null at runtime in ascx.

Good afternoon,

Here is my problem.  I am working on a site wherein I need to be able to add complex objects at run-time to the aspx page.  To that end, I have been working with ASCX files and it seems to be the right direction, however, elements that I add at design time return nothing once I call a new UserControl from codebehind.  In the sample below, the control never shows in the browser and the uc.Label1 = nothing at runtime, please help and thank you in advance.

Simple code-sample below.

WebUserControl1.ascx
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="WebApplication3.WebUserControl1" %>
<asp:Label ID="Label1" runat="server" Text="Hi am on a control"></asp:Label>

Open in new window


Default.aspx.vb
Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim uc As New WebUserControl1
            Panel1.Controls.Add(uc)
        End If
    End Sub

End Class

Open in new window

Default.aspx
<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
    CodeBehind="Default.aspx.vb" Inherits="WebApplication3._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
</asp:Content>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rouchie
Rouchie
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Dim uc As New WebUserControl1
uc = CType(LoadControl("~/Path/to/WebUserControl1.ascx"), WebUserControl1)
Panel1.Controls.Add(uc)

Open in new window

Hi

To load a user control, use the below code

 ' Load the control
        Dim myUC As UserControl = LoadControl("WebUserControl1.ascx")

        panel1.Controls.Add(myUC)

Open in new window

A bit late! :-Þ
Avatar of jitendra patil
try this way

Public Class _Default
    Inherits System.Web.UI.Page
    Private Mycontrol As WebUserControl1

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Page.IsPostBack Then
                Mycontrol = CType(LoadControl("WebUserControl1.ascx"), WebUserControl1)
                Panel1.Controls.Add(Mycontrol)
            End If

        End If
    End Sub
 End Class

the above code is tested and works fine .

hope this helps.