Question

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

Was it helpful?

Solution

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 Prefer composition over inheritance?

OTHER TIPS

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top