views:

27

answers:

2

Hi,

I have my own custom class which inherits from DropDownList. Is there a way to override Items.Add procedure? How?

A: 

You can't override the default Add functionality -- ListItemCollection is sealed -- but you could write an extension method that extends the ListItemCollection class. Here's an example:

namespace Truthseeker.Extensions
{
    using System.Web.UI.WebControls;

    public static class ListItemCollectionExtensions
    {
        public static void Add(
            this ListItemCollection collection, 
            ListItem item, 
            string extraParameter)
        {
            if (extraParameter.Contains("Add"))
                collection.Add(item);
        }
    }
}

You can then write something like:

DropDownList ddl = new DropDownList();
ddl.Items.Add(new ListItem("text", "value"), "Add");
Warren
+1  A: 

Is there a specific reason why you want to inherit from this class, as in are you providing this class to an interface? If the answer is no then you really should use composition over inheritance; then your problem wouldn't exist.

see http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance

Mark
+1 Good link :)
IrishChieftain