代码之家  ›  专栏  ›  技术社区  ›  Ben Hoffman

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

  •  0
  • Ben Hoffman  · 技术社区  · 14 年前

    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> 控制当我尝试在页面上设置文本时出错。是什么原因造成的?我猜 base.Construct()

    2 回复  |  直到 14 年前
        1
  •  1
  •   Tim Hoolihan    14 年前

    继承构造函数的正确方法如下:

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

        2
  •  0
  •   Coding Flow    14 年前

    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;
    }
    
    推荐文章