Ive been playing around with the default ASP.NET web application template and the following code throws an exception:
Object reference not set to an instance of an object.
when clicking the created button.
Can anyone offer a technical explanation?
Note 1: The markup is just a blank page with a placeholder in it - see below.
Note 2: Substituting Button
for LinkButton
, and the code does not throw an exception and works.
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" });
}
}
Markup:
<%@ 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>