c# - 如果 Usercontrol 位于 Repeater 中,则不会初始化 Usercontrol 中的控件

标签 c# asp.net .net

我有一种情况,我在页面上的 2 个地方使用了一些标记,其中一个在转发器中。中继器中的那个没有初始化它的子控件;他们保持为空。

默认.aspx:

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="nestedcontroltest._Default" %>
<%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <asp:Repeater runat="server" ID="rptLetters" OnItemDataBound="rptLetters_ItemDataBound">
            <ItemTemplate>
                <a:MyControl runat="server" ID="ctrlMyControl"/>
            </ItemTemplate>
        </asp:Repeater>
    </body>
</html>

Default.aspx.cs:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        rptLetters.DataSource = new[] { "a", "b", "c" };
        rptLetters.DataBind();
    }

    public void rptLetters_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        var ctrlMyControl = (MyControl)e.Item.FindControl("ctrlMyControl");
        ctrlMyControl.Text = e.Item.DataItem.ToString();
    }
}

我的控件.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="nestedcontroltest.MyControl" %>
<asp:Panel runat="server" ID="pnlContent">
    <asp:Literal runat="server" ID="ltlText"/>
</asp:Panel>

我的控件.ascx.cs:

public partial class MyControl : UserControl
{
    public string Text { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        ltlText.Text = Text;
    }
}

当我尝试加载它时,我得到“对象引用未设置为对象的实例”。 - 显然 ltlText 为空。

如何让我的 UserControl 正确初始化?

最佳答案

找到答案:

  1. 中继器与问题无关。
  2. 在 Default.aspx 中,我需要按名称而不是按 namespace 注册控件。

    <%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %>
    

    需要改成

    <%@ Register TagPrefix="a" TagName="MyControl" Src="~/MyControl.ascx" %>
    

然后控件会正确初始化,即使它在中继器中也是如此。也许是 ASP.net 中的错误,或者我可能需要使用完整的程序集名称?无论如何,感谢大家的帮助。

关于c# - 如果 Usercontrol 位于 Repeater 中,则不会初始化 Usercontrol 中的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11682435/

相关文章:

c# - 异常返回 : unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

c# - 如何查找用户是否是第一次登录 - C#

asp.net - Asp.net 中的 session

c# - 使用 ASP.NET MVC 验证 VIN 号

.net - Kendo 网格聚合总和显示空页脚

c# - 用 C# 编写插件或插件框架

c# - 正则表达式替换所有函数

c# - 依赖注入(inject)不只是将问题转移到别处吗?

C# :how to have message box within an event handler that freezes the application until Ok is pressed?

c# - 在 Windows 8 应用商店中使用 C# 选择控件时更改边框颜色