Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind ASP TextBox's Text to its ToolTip?

Tags:

c#

asp.net

I would like to the ToolTip always be the same as the ASP TextBox's Text. Of course I can write

AnyTextBox.Text = "any text";
AnyTextBox.ToolTip = "any text";

but I do not want to duplicate hundreds of assignment statements. I also could write change event handlers for the Text property, but I do not want to write dozens of event handlers just for this (if there is a more elegant solution)

Is there? Something like this:

<asp:TextBox ID="AnyTextBox" runat="server" ToolTip="binding magic goes here, but how?">

Thx in advance

like image 926
g.pickardou Avatar asked Jan 31 '26 00:01

g.pickardou


2 Answers

You could write your own custom control which inherits from TextBox? I used the Text property to set the tooltip, but you can do it the other way around if you want.

Control:

public class TooltipTextBox : TextBox {
    public new string Text {
        get { return base.Text; }
        set
        {
            base.Text = value;
            this.ToolTip = value;
        }
    }
}

Markup:

<my:TooltipTextBox ID="AnyTextBox" runat="server" Text="binding magic goes here">
like image 187
CodingIntrigue Avatar answered Feb 02 '26 12:02

CodingIntrigue


As far as i know there is no such automatism. For what it's worth, maybe you can use PreRender:

protected void Page_PreRender(Object sender, EventArgs e)
{
    var allTextControlsWithTooltips = new List<WebControl>();
    var stack = new Stack<Control>(this.Controls.Cast<Control>());
    while (stack.Count > 0)
    {
        Control currentControl = stack.Pop();
        if (currentControl is WebControl && currentControl is ITextControl)
            allTextControlsWithTooltips.Add((WebControl)currentControl);
        foreach (Control control in currentControl.Controls)
            stack.Push(control);
    }
    foreach (var txt in allTextControlsWithTooltips)
        txt.ToolTip = ((ITextControl)txt).Text;
}

You could also use a UserControl which handles this event, then you just need to put it on all of the pages that should behave in this way. Or you could let all pages inherit from one base page.

like image 20
Tim Schmelter Avatar answered Feb 02 '26 13:02

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!