[英]Problem Creating Instances of ASP.NET User Controls Programmatically
我可以使用以下代码以编程的方式创建控件,而不会出现问题:
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()
可以解决这个问题,但显然没有。
继承构造函数的正确方法如下:
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 ... //
}
这样更改构造函数是否可以解决问题?
我不确定调用base.Contruct()
是否是您应该做的,请尝试调用以下基类示例的默认构造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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.