我有一个非常奇怪的问题。我有一个 UserControl,里面有一些控件。我想在另一个回发中引用这些控件。但是当我尝试获取它们时Controls
,我的控件的属性返回 null。我正在研究vs2008。
这是示例代码:
public partial class MyUserControl : System.Web.UI.UserControl, INamingContainer
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
Response.Write(control.ClientID);
}
}
private void MyTable()
{
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
CheckBox check = new CheckBox();
check.ID = "theId";
check.Text = "My Check";
check.AutoPostBack = true;
cell.Controls.Add(check);
row.Cells.Add(cell);
check = new CheckBox();
check.ID = "theOther";
check.AutoPostBack = true;
check.Text = "My Other Check";
cell = new TableCell();
cell.Controls.Add(check);
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
protected override void Render(HtmlTextWriter writer)
{
MyTable();
base.Render(writer);
}
}
Default.aspx 页面类似于:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.cs" Inherits="Tester.Default" %>
<%@ Register TagPrefix="uc1" TagName="MyControl" Src="~/MyUserControl.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Unbenannte Seite</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:MyControl ID="MyControlInstance" runat="server" />
</div>
</form>
</body>
</html>
我不知道我是否迷失在 ASP.NET 生命周期的某些部分。但这种情况让我抓狂。任何帮助将不胜感激。