Search code examples
c#overridingextendasp.net-webcontrol

Overriding "Text" property of a control extended from Button using C#


I'm having a problem extending the standard WebControls.Button control. I need to override the text property, but I receive the error message:

cannot override inhereted member 'System.Web.UI.WebControls.Button.Text.get' because it is not marked virtual, abstract or override

I used the following code for a LinkButton, and that worked perfectly:

public class IconLinkButton : LinkButton
{
    private string _icon = "";
    public string Icon
    {
        get
        {
            return _icon;
        }
        set
        {
            _icon = value;
        }
    }

    public override string Text
    {
        get
        {
            return "<i class=\""+Icon+"\"></i> " + base.Text;
        }
        set
        {
            base.Text = value;
        }
    }
}

However, doing the same thing for a standard Button kicks up the error I described above.

public class IconButton : Button
{
    private string _icon = "";
    public string Icon
    {
        get
        {
            return _icon;
        }
        set
        {
            _icon = value;
        }
    }

    public virtual string Text
    {
        get
        {
            return "<i class=\"" + Icon + "\"></i> " + base.Text;
        }
        set
        {
            base.Text = value;
        }
    }
}

How can I fix this?


Solution

  • This is because LinkButton has a virtual Text property.. whilst Button does not.

    You can hide the base functionality entirely by using new:

    public class IconButton : Button {
        public new string Text {
            // implementation
        }
    }
    

    Using new hides the inherited member completely.