我一直在使用默认的 ASP.NET Web 应用程序模板,以下代码引发异常:
你调用的对象是空的。
单击创建的按钮时。
谁能提供技术解释?
注意 1:标记只是一个带有占位符的空白页面 - 见下文。
注意2:替换Button
为LinkButton
,代码不会抛出异常并且可以正常工作。
public partial class test : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
foo();
}
protected override void OnLoad(EventArgs e)
{
foo();
}
protected void foo()
{
placeholder1.Controls.Clear();
placeholder1.Controls.Add(new Button() { Text = "test", ID = "btn" });
}
}
标记:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebApplication1.test" %>
<!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">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server" ID="placeholder1" />
</div>
</form>
</body>
</html>