C
C
Chvalov2014-10-08 18:47:44
IDE
Chvalov, 2014-10-08 18:47:44

How to set Placeholder for TextBox in VisualStudio 2013 C# language?

Hello wrote on Delphi in XE7 there was a property in the placeholder text field.
I wanted to switch to C# and ran into the fact that this property is missing here :-(
How to be in this case?
Can you make it so that when you click on the text field, the text is deleted, and if the user enters text and when you accidentally click on the input field, it does not delete it text

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
aush, 2014-10-08
@aush

Because the framework is not specified, it must be assumed that by default we have WinForms. Then in its simplest form it looks like this:

class TextBoxWithPlaceholder : TextBox
{
    public string Placeholder { get; set; }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        if (!DesignMode)
        {
            Text = Placeholder;
        }
    }

    protected override void OnLostFocus(EventArgs e)
    {
        base.OnLostFocus(e);

        if (Text.Equals(string.Empty))
        {
            Text = Placeholder;
        }
    }

    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);

        if (Text.Equals(Placeholder))
        {
            Text = string.Empty;
        }
    }
}

L
lam0x86, 2014-10-08
@lam0x86

If WinForms, then, starting with WinXP, support for this feature is built into the OS, and this is called Cue Banners. Here it is written how it can be screwed: stackoverflow.com/a/4902969
If WPF, then you can see here: stackoverflow.com/a/833967

I
idSergey, 2014-10-08
@idSergey

You can play around with your ideas, make a control, also look at the events there are a lot of them, I would remove the text provided that the field is empty and put a placeholder, and remove the placeholder when the focus is on, you can turn on the flag and check through it. Bunch of ideas.
You can also see the controls with the implementation.
Good luck:)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question