Camenwolf
Camenwolf

Reputation: 798

Why does this composite control not render its child controls?

IDE: Visual Studio 2010 Framework: .net 3.5 WebServer: Visual Studio Dev Server

I'm trying to get a grasp of custom controls and composite controls. The code below has been produced more or less directly from examples I've found in various tutorials. I have registered the control on my page and in my toolbox. I can drag the control on the page and it displays the text property properly, but it does not render my button, textbox, or dropdown list. Can someone look at this code and tell me why these items do not render on my page?

Thank you for reading

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HancockControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:PeoplePicker runat=server></{0}:PeoplePicker>")]
    public class PeoplePicker : CompositeControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]

        protected TextBox txtName = new TextBox();
        protected DropDownList ddlResults = new DropDownList();
        protected Button btnSearch = new Button();

        public string Text
        {
            get
            {
                EnsureChildControls();
                String s = (String)ViewState["Text"];
                return ((s == null) ? "[Text]" : s);
            }

            set
            {
                EnsureChildControls();
                ViewState["Text"] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(Text);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            btnSearch.Text = "Search";
            this.Controls.Add(txtName);
            this.Controls.Add(ddlResults);
            this.Controls.Add(btnSearch);
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            base.RenderControl(writer);
        }
    }
}

Upvotes: 0

Views: 395

Answers (1)

Camenwolf
Camenwolf

Reputation: 798

Answering my own question here in case anyone benefits from it in the future...

The problem with my code above apparently is that when inheriting from the CompositeControl class vice the WebControl class I needed to comment out or delete the RenderControl method. CompositeControl seems to only use the CreateChildControls method to render itself and the RenderControl method causes it to... I don't know... not render somehow.

Use CreateChildControls and any literal text or html elements that need to be added to the control can be added by defining and using a LiteralControl.

Upvotes: 1

Related Questions