2010-08-11 87 views
2

用法:Web用戶控件的內容裏面

<uc1:WindowControl ID="Window_ExpoNews" runat="server" Height="265px" Title="Expo News" 
    Width="100%">    
    <ContentTemplate> 
     This content will show in the center cell of this user control. 
     <br /> 
     I can even add real controls. 
     <asp:TextBox ID="TextBox1" runat="server" /> 
     <br /> 
     Good times. 
    </ContentTemplate> 
</uc1:WindowControl> 

控制的來源:

<asp:Panel ID="Panel2" 
      runat="server">     
     </div> 
</asp:Panel> 
<asp:PlaceHolder runat="server" ID="BodyControlSpace"/> 

代碼背後:

public partial class Componants_WebUserControl : System.Web.UI.UserControl{ 

private ITemplate _ContentTemplate; 

[PersistenceMode(PersistenceMode.InnerProperty)] 
public ITemplate ContentTemplate 
{ 
    get { return _ContentTemplate; } 
    set { _ContentTemplate = value; } 
} 

protected override void OnInit(EventArgs e) 
{ 
    base.OnInit(e); 
    _ContentTemplate.InstantiateIn(BodyControlSpace); 
} 

public Unit Width 
{ 
    get {return Panel1.Width;} 
    set {Panel1.Width = value;} 
} 

public Unit Height 
{ 
    get {return Panel1.Height;} 
    set {Panel1.Height = value;} 
} 

public string Title 
{ 
    get {return lblTitle.Text;} 
    set {lblTitle.Text = value;} 
} 

}

的問題是它給我跟隨錯誤:
未將對象引用設置爲對象的實例。 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。

異常詳細信息:System.NullReferenceException:未將對象引用設置爲對象的實例。

源錯誤:

線21:{
第22行:base.OnInit(E);
第23行:_ContentTemplate.InstantiateIn(BodyControlSpace);
第24行:}
第25行:

+0

我有同樣的問題,這個工程,當我用這種方法作爲用戶控件,但是當我試圖將其轉換爲控件。一樣的問題。 – 2012-04-17 13:40:30

回答

0

怎麼樣在你的web控制面板從類派生。它會給你和div圍繞你的控制,但也會讓你把內容放進去。試試這樣:

public WindowControl : Panel 
{ 
    // ... 
} 

或者,如果你不想在你的HTML任何額外的變化使用文字作爲基本控制:

public WindowControl : Literal 
{ 
    // ... 
} 
1

終於,我發現它沒有人說我,我可以加上「如果「在那裏:

protected override void OnInit(EventArgs e) 
{ 
    base.OnInit(e); 
    if (_ContentTemplate != null) 
     _ContentTemplate.InstantiateIn(BodyControlSpace); 
} 
+1

我很高興你找到了解決方案 – MUG4N 2010-08-11 08:39:13

相關問題