Search code examples
asp.netuser-controlscode-behind

ASP.NET Can't access user control's property in code-behind file


Visual Studio 2008, C#, ASP.NET

Need to make multiple copies (or instances) of a web user control programmatically.

I have UserControlFile.ascx which contains an asp:Label with ID="vhLabel" in it. In that file I set label's Text property through public string vhText variable, as usual:

public string vhText
{
    set
    {
        vhLabel.Text = value;
    }
}

There are also some divs and other html data in this file that cannot be created in C# programmatically, so I have to use ascx file.

Now, in code-behind file I need to:

  1. clone this user control many times;
  2. set unique value to label's property "Text" of each clone through "vhText" variable.

Please, share your suggestions on these issues. If you need, I can show my code here. I've been looking for an answer for very long, but still unsuccessful.


Solution

  • You can find a walkthrough of how to programmatically add user controls to your page here: http://msdn.microsoft.com/en-us/library/c0az2h86(v=vs.100).aspx

    In your case, you need something like this in your UserControlFile.ascx control (the className attribute is the important bit):

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControlFile.ascx.cs" Inherits="UserControlFile" className="MyUserControl" %>
    <asp:Label ID="vhLabel" runat="server"></asp:Label>
    

    Then, at the top of your page that will include the control (change the file path appropriate to your structure):

    <%@ Reference Control="~/Controls/UserControlFile.ascx" %>
    

    Finally, the code behind of the page will contain the code to programmatically add the instances of the control via the LoadControl method and the use of the MyUserControl type - defined in the className attribute in the @Control directive above:

    protected void Page_Load(object sender, EventArgs e)
    {
        var control = (ASP.MyUserControl)LoadControl("~/Controls/UserControlFile.ascx");
        control.vhText = "1";
        Page.Controls.Add(control);
    
        control = (ASP.MyUserControl)LoadControl("~/Controls/UserControlFile.ascx");
        control.vhText = "2";
        Page.Controls.Add(control);
    
        /* etc... */
    }
    

    That should point you in the right direction...