2010-07-19 60 views
0

我能夠創建控件親們語法使用下面的代碼沒有問題:問題創建ASP.NET用戶的實例編程控制

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()會解決這個問題,但它顯然沒有。

回答

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

是否改變你的構造一樣,解決這個問題?

+0

我仍然得到一個錯誤'對象引用未設置爲實例一個對象。「出於同樣的原因,即使使用:base() – 2010-07-19 14:49:15

+0

你的第一個代碼片段,你創建和添加控件...你在做什麼? – 2010-07-19 15:01:18

+0

我正在從'Page_Load'做它 – 2010-07-19 15:17:38

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

即使使用:base(),我仍然會得到一個錯誤:「對象引用未設置爲對象的實例。」出於同樣的原因。 – 2010-07-19 14:48:43