简体   繁体   中英

Web User Control with content inside it

Usage :

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

Control's source :

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

Code Behind :

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

}

The problem is it gives me following error :
Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 21: {
Line 22: base.OnInit(e);
Line 23: _ContentTemplate.InstantiateIn(BodyControlSpace);
Line 24: }
Line 25:

finally I found it nobody said me I can add "if" over there :

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

What about deriving from panel class in your web control. It will give you and div around your control but also will avaible you to put content inside. Try like this:

public WindowControl : Panel
{
   // ...
}

Alternatively if you don't want any extra changes in your html use Literal as a base control:

public WindowControl : Literal
{
   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM