Kyle Sletten
Kyle Sletten

Reputation: 5413

Overriding HyperLink.Text property doesn't work correctly

I'm trying to work on a sub-class of System.Web.UI.WebControls.HyperLink in C# and I want to be able to specify a default text property that will replace the text value in certain conditions.

public class MyHyperLink : HyperLink
{
    public string DefaultText { get; set; }

    public override string Text
    {
        get
        {
            return string.IsNullOrEmpty(base.Text)
                ? (this.DefaultText ?? string.Empty)
                : base.Text;
        }
    }
}

When I used this code my hyperlink rendered on the page but instead of <a>Default Text</a> I got <a text="Default Text"></a>.

Upvotes: 0

Views: 362

Answers (3)

mathieu
mathieu

Reputation: 31202

According to reflector, you did miss an attribute, and did not override the setter

public class MyHyperLink : HyperLink
{
    public string DefaultText { get; set; }

    [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
    public override string Text
    {
        get
        {
            return string.IsNullOrEmpty(base.Text) ? this.DefaultText : base.Text;
        }
        set
        {
            base.Text = value;
        }
    }
}

Upvotes: 1

BritishDeveloper
BritishDeveloper

Reputation: 13359

You're completely overriding the behaviour of the Text property though so it may well not render how it was designed to. What you really want to do is override the Render method:

protected override void Render(HtmlTextWriter writer)
{
    if (string.IsNullOrEmpty(base.Text))
    {
        Text = (this.DefaultText ?? string.Empty);
    }
    base.Render(writer);
}

This is cutting in just before the control renders to change the Text around. It is happening so late in the control lifecycle it isn't even going to be saved in ViewState to save bloating!

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

you don't need to override the Text property. You just need add a new string property and decorate that with the attribute PersistenceMode as showed below:

[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public string MyTextProperty{
    get
    {
       return ViewState["Text"] != null ? (string)ViewState["Text"] : string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}

Upvotes: 1

Related Questions