views:

1275

answers:

3

I'm just getting started with Custom User Controls in c# and I'm wondering if there is any examples out there of how to write one which accepts nested tags. For example, when you create an "asp:repeater" you can add a nested tag for "itemtemplate".

Any help appeciated!

Cheers

+7  A: 

I'm not sure if it's considered poor form to link to something I wrote on my blog, but take a look at this. It was mostly a reminder to myself, but I think it reads fairly well! :=)

Rob
Don't think it's poor form at all if it answers the question. It's when people write blog posts ONLY post. That's when it's insane making. Have a click.
IainMH
Thank You! Thank You! Thank You!
Luis
@Luis, glad I could help =)
Rob
+1  A: 

My guess is you're looking for something like this? http://msdn.microsoft.com/en-us/library/aa478964.aspx

Your tags were removed or are invisible, so can't really help you there.

hokkaido
+1  A: 

I followed Rob's blog post, and made a slightly different control. The control is a conditional one, really just like an if-clause:

<wc:PriceInfo runat="server" ID="PriceInfo">
    <IfDiscount>
        You don't have a discount.
    </IfDiscount>
    <IfNotDiscount>
        Lucky you, <b>you have a discount!</b>
    </IfNotDiscount>
</wc:PriceInfo>

In the code I then set the HasDiscount property of the control to a boolean, which decides which clause is rendered.

The big difference from Rob's solution, is that the clauses within the control really can hold arbitrary HTML/ASPX code.

And here is the code for the control:

using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebUtilities
{
    [ToolboxData("<{0}:PriceInfo runat=server></{0}:PriceInfo>")]
    public class PriceInfo : WebControl, INamingContainer
    {
        private readonly Control ifDiscountControl = new Control();
        private readonly Control ifNotDiscountControl = new Control();

        public bool HasDiscount { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Control IfDiscount
        {
            get { return ifDiscountControl; }
        }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Control IfNotDiscount
        {
            get { return ifNotDiscountControl; }
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            if (HasDiscount)
                ifDiscountControl.RenderControl(writer);
            else
                ifNotDiscountControl.RenderControl(writer);
        }
    }
}
Guðmundur H