Question

The Usercontrol I am creating is made up of 3 files as expected (ascx, ascx.cs, and ascx.designer.cs)

My Problem :

Controls created in the aspx page ( asp:Button runat="server" id="mybutton" />) are not being initialized properly, such that attaching to the 'Load' event, and trying to use button, results in a null object exception

I suspect this is a Visual Studio problem, either weird bug or unusal setting, but it wouldn't surprise me if I'm doing something silly.

My attempted work-a-arounds

  1. I've copied another working User control from a different project into this project in visual studio and it too does not work (controls defined in ascx page are null in load event in code behind page, though they work fine where I copied them from)

  2. I'm using the 'CreateChildControls()' method, as I've done in some other composite controls, but then everything is still null in the load and init events

  3. I've created a seperate solution and project file, and added all the files and references, but still, this does not help the situation.

It appears to me that the 'page life cycle' (control life cycle?) is not initializing the controls properly for some reason, but cant see why, please someone help.

Posting my code as request :

PersonalDetails.aspx
    <cwpEditControl:PersonalDetails runat="server" id="edtPersonalDetails" />

PersonalDetails.ascx
    <%@ Control Language="C#" CodeBehind="PersonalDetails.ascx.cs" Inherits="company.web.CustomerWebPortal.controls.edit.PersonalDetails" %>        
    <asp:Button runat="server" ID="myTestButton" />         

PersonalDetails.ascx.cs
    public PersonalDetails()
    {         
        this.Load += new EventHandler(PersonalDetails_Load);
    }

    void PersonalDetails_Load(object sender, EventArgs e)
    {
        this.myTestButton.Text = "Submit";  //this line creates an exception!
    }

PersonalDetails.ascx.designer.cs
    protected global::System.Web.UI.WebControls.Button myTestButton;
Was it helpful?

Solution

I have fixed my problem by adding to the web.config file, basically 'registering' my custom control across the entire web application I am creating :

<pages>
  <controls>
    <add tagPrefix="scottgu" src="~/Controls/Header.ascx" tagName="header"/>
    <add tagPrefix="scottgu" src="~/Controls/Footer.ascx" tagName="footer"/>
    <add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
  </controls>
</pages>

link explaining the additions to the web.config file (please note this article does not address my problem directly)

http://weblogs.asp.net/scottgu/archive/2006/11/26/tip-trick-how-to-register-user-controls-and-custom-controls-in-web-config.aspx

I dont personally feel the 'site wide' declaration of my custom control should be required, but it fixes the problem so I'm using it, but would still like to me enlightened as to the reason why it is required to be done that way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top