Inheritance and partial classes...

AK_00 used Ask the Experts™
Okay, so I have the following pages using 1.1 style code behind and inheritance fine, but not working with 2.0. Here is the 1.1 code:

- search.aspx.cs
public class SearchTemplate : System.Web.UI.Page
   public Literal warningMsg;
  //other controls here

  void Page_Load(Object sender, EventArgs e)
    warningMsg.Text = "Page Loaded Ok";
    //other code here

  //other methods etc

- customsearch.aspx.cs
public class CustomSearch : SearchTemplate
  //controls here

  //other methods etc

- customsearch.aspx
<%@ Page Language="C#" src="customsearch.aspx.cs" Inherits="CustomSearch" MasterPageFile="search.master" Buffer="true" %>
<!-- other page code here -->

So customsearch.aspx uses customsearch.aspx.cs as it's code behind, which inherits fromt he SearchTemplate class in search.cs. This is all fine. The warningMsg control in the customsearch.aspx page gets set on load, as you would expect.

So now, I decided to use partial classes, ASP.NET 2 style
 - I changed the customsearch.aspx header to use CodeFile= instead of src=
 - I removed the control declarations from customsearch.aspx.cs and declared it as a partial class
 - I removed the control declarations from search.aspx.cs and declared it as a partial class.

I am getting an error when I try to view the page - Object reference not set to an instance of an object. this is caused by the 'warningMsg=' line in the page load of search.aspx.cs. I know this because *everything* else has been commented out, and the page will load if I also comment out this line.

So why is this occuring? The warningMsg control does exist on the customsearch.aspx page, but seems to be 'out of scope' in the parent class of the code behind.

Why does it find the control on the page in 1.1 style, but tell me it doesn't exist in 2.0 style? What am I doing wrong?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
when you say you changed to partial class did it look like this?

public partial class CustomSearch : System.Web.UI.Page, SearchTemplate


No... it looks like:

public partial class CustomSearch : SearchTemplate

I figure it should inherit System.Web.UI.Page through SearchTemplate anyway, which reads:

public partial class SearchTemplate : System.Web.UI.Page

But I tried it anyway, and puitting:

public partial class CustomSearch : System.Web.UI.Page, SearchTemplate

will throw an error that I can't use multiple base classes.


Have now solved this.

The solution was to use
in the customsearch.aspx header. This allows the controls to be found correctly.
PAQed with points refunded (500)

EE Admin

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial