我有一种情况,我在一个页面上的2个位置使用一些标记,其中一个在转发器中.转发器中的那个没有初始化其子控件; 他们保持无效.
Default.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>
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
MyControl.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>
Run Code Online (Sandbox Code Playgroud)
MyControl.ascx.cs:
public partial class MyControl : UserControl
{
public string Text { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
ltlText.Text = Text;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试加载它时,我得到"对象引用未设置为对象的实例". - 显然ltlText为null.
如何让我的UserControl正确初始化?
找到答案:
在Default.aspx中,我需要通过名称而不是命名空间来注册控件.
<%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %>
Run Code Online (Sandbox Code Playgroud)
需要改为
<%@ Register TagPrefix="a" TagName="MyControl" Src="~/MyControl.ascx" %>
Run Code Online (Sandbox Code Playgroud)然后控件就会正确初始化,即使它在转发器中也是如此.也许是ASP.net中的一个错误,或者我需要使用完整的程序集名称?无论如何,感谢所有帮助人员.
| 归档时间: |
|
| 查看次数: |
3749 次 |
| 最近记录: |