Search code examples
asp.netaspx-user-control

How to change the properties of controls in a UserControl at runtime in WebForms


I have a simple UserControl defined as:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AdminBanner.ascx.cs" Inherits="OrderManager.Controls.AdminBanner" %>

<asp:Panel runat="server" ID="AlertPanel" BorderWidth="1px">
    <asp:Label runat="server" ID="LabelTitle" Text="Test!!!!!!!" ></asp:Label>
</asp:Panel>

I include the UserControl on an aspx page like so:

                <table style="width: 100%;">
                    <tr>
                        <td>
                            <asp:Panel ID="PanelPreviewBanner" Visible="False" runat="server">
                                <OrderManager:AdminBanner  Id="AdminBanner" Visible="True" runat="server" />
                            </asp:Panel>
                        </td>
                    </tr>
                </table>

When I click a button on the web form, I want to not only display the Panel, but also change the default value of the LabelTitle in the UserControl. I can show the Panel like this:

                // Display the Preview Panel.
                this.PanelPreviewBanner.Visible = true;

If I try to change the LabelTitle of the USerControl, wither using the ID of the UC or by way of a property in the UserControl, I always get an error stating that the control is null.

My ultimate goal is to be able to set the css class and style on objects defined in my UserControl.

I have tried numerous examples I found here and through Google and nothing works.


Solution

  • I am assuming you've already done this -

    1. A public property in your AdminBanner.ascx.cs that exposes label's text property to be set by the parent page
    public string LabelTitleValue
    {
        get { return LabelTitle.Text; }
        set { LabelTitle.Text = value; }
    }
    
    1. Below is how you should be able to get/set the usercontrol's label text.
    AdminBanner.LabelTitleValue = "Test changed";
    var text = AdminBanner.LabelTitleValue;
    

    In case you've already done this, you may first try removing your user-control outside the panel (something like below) and at least confirm that user-control is being displayed.

    <td>
       <asp:Panel ID="PanelPreviewBanner" Visible="False" runat="server"></asp:Panel>
       <OrderManager:AdminBanner  Id="AdminBanner" Visible="True" runat="server" />
    </td>
    

    If it's displaying properly, you may do below in addition to setting panel's visibility

    // Display the Preview Panel.
    this.PanelPreviewBanner.Visible = true;
    this.AdminBanner.Visible = true;