tags:

views:

32

answers:

2

I am able to create controls pro grammatically using the code below without issue:

FileListReader fReader = (FileListReader)LoadControl("~/Controls/FileListReader.ascx");
phFileLists.Controls.Add(fReader);

However, I would like to change the control so that I can give it a constructor like this:

public FileListReader(Int32 itemGroupId, Int32 documentType, String HeaderString, String FooterString, bool isAdminUser)
{
    base.Construct();
    this.itemGroupId = itemGroupId;
    this.documentType = documentType;
    this.HeaderString = HeaderString;
    this.FooterString = FooterString;
    this.isAdminUser = isAdminUser;
}

and then I should be able to call the control like this:

FileListReader fReader = (FileListReader)LoadControl(typeof(FileListReader), new Object[] { itemGroupId, 6, "Sell Sheets", "<br /><br />", isAdminUser });

However, when I do this I always get an error that my in page controls within my FileListReader Control have not been instantiated and I get a null reference error. So for example I have an <asp:Label></asp:label> control that errors out when I try to set it's text on the Page_Load method. What is causing this? I figured the base.Construct() would have solved this issue but it obviously has not.

+1  A: 

The proper way to inherit a constructor is like this:

class FileListReader : WebControl
{
public FileListReader(Int32 itemGroupId, 
                          Int32 documentType, 
                          String HeaderString, 
                          String FooterString, 
                          bool isAdminUser) : base()  // <-- notice the inherit
{

    this.itemGroupId = itemGroupId;
    this.documentType = documentType;
    this.HeaderString = HeaderString;
    this.FooterString = FooterString;
    this.isAdminUser = isAdminUser;
}
  // ... other code here ... //
}

Does changing your constructor like that fix the issue?

Tim Hoolihan
I still get an error `Object reference not set to an instance of an object.` for the same reason, even with the :base()
RandomBen
your first code snippet, where you create and add the control... what method are you doing that in?
Tim Hoolihan
I am doing it from `Page_Load`
RandomBen
Also, my class is `public partial class FileListReader : System.Web.UI.UserControl`. I don't know if that makes a difference.
RandomBen
A: 

I am not sure that calling base.Contruct() is what you should be doing, try calling the default contructor of the base class example below:

public FileListReader(Int32 itemGroupId, Int32 documentType, String HeaderString, String FooterString, bool isAdminUser) :base()
{
    base.Construct();
    this.itemGroupId = itemGroupId;
    this.documentType = documentType;
    this.HeaderString = HeaderString;
    this.FooterString = FooterString;
    this.isAdminUser = isAdminUser;
}
Ben Robinson
I still get an error `Object reference not set to an instance of an object.` for the same reason, even with the :base()
RandomBen