问题以编程方式创建ASP.NET用户控件的实例

时间:2010-07-19 14:18:26

标签: c# asp.net-3.5

我能够使用以下代码以编程方式创建控件而不会出现问题:

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

但是,我想更改控件,以便我可以给它一个这样的构造函数:

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;
}

然后我应该能够像这样调用控件:

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

然而,当我这样做时,我总是得到一个错误,我的FileListReader控件中的页面控件尚未实例化,我得到一个空引用错误。所以例如我有一个<asp:Label></asp:label>控件,当我尝试在Page_Load方法上设置它的文本时会出错。是什么造成的?我认为base.Construct()会解决这个问题,但显然没有。

2 个答案:

答案 0 :(得分:1)

继承构造函数的正确方法是这样的:

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 ... //
}

更改你的构造函数是否可以解决问题?

答案 1 :(得分:0)

我不确定调用base.Contruct()是你应该做的,尝试调用下面基类示例的默认构造函数:

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;
}