views:

750

answers:

1

hi, i have a base user control (WC1) which inherits from WebUserControl and a child user control (WC2) which inherits from WC1. I added a textBox and a label to WC1 in vs design view not code behind. But all the server controls that i put in WC1 are null and give null pointer exception.I tried to access textBox and label in different events but the all of them are null.

Anyone knows what went wrong here?thanks.

Steps to reproduce the error:

  1. create a web user control called WC1 by add a new item in VS
  2. added a textBox and label server control to WC1 in design view of VS and put code behind: var value = txetBox.Text;
  3. created another web user control called WC2 by add a new item in VS and change its base class to WC1 in its code behind
  4. create a web page by adding a new item in vs and drag WC2 to the design view of the page
  5. run the page then you will see the exception for the codebehind in WC1

code:

WC1: code behind: public partial class WC1: System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) {

    }
}

page:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WC1.ascx.cs" Inherits="WebApplication1.WC1" %>

WC2: code behind: public partial class WC2: WC1 { var txt = TextBox1.Text}

page:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WC2.ascx.cs" Inherits="WebApplication1.WC2" %>

To sum up my question:

can web server controls of WC1 be instantiated in this case? or can user control inherit from another user control and web server controls of parent user control be carried to its children without worring the layout?

Ok i have tested if i dont add control in WC1 codebehind, it will never be instantiated.

+1  A: 

If you didn't set the base type to WC1, then when you added the control to the markup, the controls were created in the designer.cs of WC2, and these are hiding the ones inherited from WC1.

To resolve this, just open up the designer.cs for WC2 and delete the controls, then the ones on the base class will be what the markup rigs up to on compilation. Alternative solution: make sure your base class is WC1, delete the designer, right click the .ascx, and select Convert to Web Application, this will re-generate the designer and not create those controls it finds in the base class...same effect.

If I'm misunderstanding you, and you're trying to inherit the markup of the base control....you can't do that, think of how it would render, what would be where? If it's something else all-together please post your markup and properties for both controls, that'd make it crystal clear what's going on.

Nick Craver
Inheriting the markup could be done similar to how an overriding method calls base.method(). For example, a placeholder WC2 that renders the markup from WC1. If WC2 has not such placeholder, then no markup is inherited.
Doug D