Tonight as I was experimenting with Beta 2 I ran into some troubles with my pages that inherit from a base page class. All the controls that we’re being setup in the base page class were throwing NullReference exceptions.
MyPage.aspx inherits MyPage inherits MyBasePage
MyPage.aspx and MyPage.aspx.cs don’t need controls defined since they are partial classes and have the magic that goes along with being setup as such. The MyBasePage class however isn’t a partial class since it lives in a completely different location (different assembly). In that base page class I have protected Button saveButton defined, but it’s always null. What’s the magic step that’s necessary to be able to get a reference to the saveButton from within my base page class?
UPDATE: Well I was able to retrieve a reference to the controls by doing a this.FindControl within the Init of the page. This isn’t a terrible change, but, I am wondering if it’s the answer to how to support this. To provide a little more context.
In 1.1 I had a base page EditPage.cs with the following declaration:
protected System.Web.UI.WebControls.Button saveButton;
protected virtual void InitializeComponent() {
this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
}
When I run this in .NET 2.0 I get a NullReferenceException, unless I do something like:
protected System.Web.UI.WebControls.Button saveButton;
protected virtual void InitializeComponent() {
this.saveButton = (Button) this.FindControl(“saveButton”);
this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
}
So what’s the scoop, is this the only way to support this or am I missing some super duper special keyword, attribute, or magic wave of the hand to get this to work?
UPDATE #2:
Source from my test is available here. I get a warning when I compile (below) and when the MyBasePage tries to setup the Click event handler a NullReferenceException is thrown.
“Warning 1 '_Default.myButton' hides inherited member 'MyBasePage.myButton'. Use the new keyword if hiding was intended. C:\Inetpub\wwwroot\AspNetv2\Default.aspx 1 1 C:\...\AspNetv2\”
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="myButton" runat="server" Text="My Button"/>
</div>
</form>
</body>
</html>
Default.aspx.cs
public partial class _Default : MyBasePage {
protected void Page_Load(object sender, EventArgs e) {
}
}
MyBasePage.cs
public class MyBasePage : System.Web.UI.Page {
public System.Web.UI.WebControls.Button myButton;
protected override void OnInit(EventArgs e) {
myButton.Click += new EventHandler(myButton_Click);
base.OnInit(e);
}
void myButton_Click(object sender, EventArgs e) {
Response.Write("Button Clicked");
}
}