Search code examples
c#asp.netuser-controls

How to dynamically load a text into a user control label in asp.net?


I want to load 2 user controls(same but with different text property). My user control consists of a label with a Function defined for text in ascx.cs

i am loading the control at run time using a panel ..here i want both the user control label to have different texts.

My .ascx file

 <asp:Label ID="uclbl" runat="server" />

My .ascx.cs file

 public string textforlabel
    {
        get { return uclbl.Text; }
        set { uclbl.Text = value; }
    }

My .aspx file

  <asp:Panel ID="panelMain" runat="server" >
   </asp:Panel>

* i have registered the the control

My .aspx.cs file

Control _dummyUserControl = (Control)Page.LoadControl("~/UserControl/User1.ascx");
        _dummyUserControl.  ; //can not find the textforlabel here
        panelMain.Controls.Add(_dummyUserControl);

Solution

  • because you are making incorrect casting, you should cast to your user control type :

    User1 _dummyUserControl = (User1)Page.LoadControl("~/UserControl/User1.ascx");
     _dummyUserControl.MyProperty = "SDfsdf"  ; //here you can find all your custom properties
    panelMain.Controls.Add(_dummyUserControl);