【问题标题】:Programmatically add an object of web user control into another user control以编程方式将 Web 用户控件的对象添加到另一个用户控件中
【发布时间】:2012-01-05 13:22:50
【问题描述】:

我有一个 Web 表单,我在其中加载了一个 Web 用户控件 (A)

当单击控件 A 上的按钮时,它会加载另一个名为 infobox 的 Web 用户控件的数组

当我将用户控件添加到 Web 用户控件 A 的控件集合中时,它不会显示。

下面是代码:控制A的按钮点击

foreach (Categories category in CategoriesDataList)
            {
                InfoBox ib = new InfoBox();
                ib.LiteralName = category.Category_Name;
                span_tempList.Controls.Add(ib);
                ib = null;           
            }   



span_tempList is a `<span>` tag with `runat=server`

InfoBox 控件的 HTML 和 cs 代码如下

 public partial class InfoBox : System.Web.UI.UserControl
    {
        protected global::System.Web.UI.WebControls.Label ltrlName = new System.Web.UI.WebControls.Label();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public InfoBox()
        {

        }

        public string LiteralName
        {
            get { return ltrlName.Text; }
            set { ltrlName.Text = value; }
        }

    }

--HTML--

<div style="width:10%;float:left;">
        <asp:Label ID="ltrlName" runat="server" Text="Label"></asp:Label>
    </div>
    <div style="width:20%;float:left;">
        <asp:Image ID="imgPicture" runat="server" ImageUrl="" />
    </div>
    <div style="width:70%;float:right;">

    </div>

还尝试向页面添加控件不起作用

【问题讨论】:

  • 你检查过Page构造函数中页面的IsPostBack属性是真是假吗?

标签: c# asp.net .net-3.5 webusercontrol


【解决方案1】:

如果要将其添加到页面的控件集合中,则不应通过构造函数创建 UserControl 的实例,而应使用 LoadControl

InfoBox ib = (InfoBox)LoadControl("InfoBox.ascx");

另外,为什么要将控件设置为null?它将在页面生命周期结束时自动释放。

【讨论】:

  • 感谢您的帮助。它帮助了我并且能够以编程方式加载控制.. 谢谢但"InfoBox.ascx.cs" 给了我错误它只是.ascx 文件路径LoadControl 要求。
猜你喜欢
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
相关资源
最近更新 更多