首页 > 解决方案 > 如何在运行时在 WebForms 中更改 UserControl 中控件的属性

问题描述

我有一个简单的 UserControl 定义为:

<%@ 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>

我在 aspx 页面上包含 UserControl,如下所示:

                <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>

当我单击 Web 表单上的按钮时,我不仅要显示 Panel,还要更改 UserControl 中 LabelTitle 的默认值。我可以这样显示面板:

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

如果我尝试更改 USerControl 的 LabelTitle、使用 UC 的 ID 或通过 UserControl 中的属性更改,我总是会收到一条错误消息,指出该控件为空。

我的最终目标是能够在我的 UserControl 中定义的对象上设置 css 类和样式。

我已经尝试了很多我在这里和通过谷歌找到的例子,但没有任何效果。

标签: asp.netaspx-user-control

解决方案


我假设你已经这样做了 -

  1. AdminBanner.ascx.cs 中的公共属性,公开标签的文本属性以由父页面设置
public string LabelTitleValue
{
    get { return LabelTitle.Text; }
    set { LabelTitle.Text = value; }
}
  1. 以下是您应该如何获取/设置用户控件的标签文本。
AdminBanner.LabelTitleValue = "Test changed";
var text = AdminBanner.LabelTitleValue;

如果您已经这样做了,您可以先尝试在面板外移除您的用户控件(如下所示),并至少确认正在显示用户控件。

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

如果它显示正确,除了设置面板的可见性之外,您还可以执行以下操作

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

推荐阅读