Ahsan Hussain
Ahsan Hussain

Reputation: 982

Clear text in Text box on clicking it

I want my TextBox's text which has already product name on it to automatically vanishes when I click on it, and I can enter the text box I want in it.

Please let me know how can I do it without loosing the data I've entered manually in it and I can get the default text whenever there is nothing entered by myself in the text box.

Upvotes: 0

Views: 3832

Answers (5)

Zuabros
Zuabros

Reputation: 270

This will work:

Go to the "properties" of your textbox. You will see a yellow lightning bolt in the first line tab. There you will find all possible events that can be triggered. Search for "Enter" or "Click" entry, double-click it. There you can put whatever you want (such as textBox1.Clear();)

Upvotes: 0

Jack Frost
Jack Frost

Reputation: 277

why use some extra software and not to use your own mind to code? here is the simple code to achieve this task

first use this:

public bool txSearch = false;

then on your text click event code:

private void txtSearch_Click(object sender, EventArgs e)
{
    txSearch = true;

    if (txtSearch.Text == "Product Name")
    {
        if (txSearch == true)
        {
            txtSearch.Text = "";
        }                   
    }
}

this will clear your field text box when you click on the text, now to write back the product name when there is nothing in your textbox and you are leaving it do this code on textbox leaving event:

private void txtSearch_Leave(object sender, EventArgs e)
{
    if (txtSearch.Text == "")  // here you can also use txtSearch.Text != "Poduct Name", but it could affect your search code possibly 
    {
        txtSearch.Text = "Product Name";  
    } 
}

Upvotes: 1

Krishna
Krishna

Reputation: 1996

You actually need a watermark for your textbox.

Please look at this answer of Watermark / hint text TextBox in WPF to implement an attached property to a textbox.

Upvotes: 0

har07
har07

Reputation: 89285

That behavior is known as watermark. You can either :

  1. Use textbox control with watermark from a library such as WPF extended toolkit
  2. Implement it your self using style and attached behavior as demonstrated in this blog post
  3. Do some trick to achieve the same behavior with simpler code, for example as shown in this codeproject post

Upvotes: 1

Herm
Herm

Reputation: 2999

You should consider using a third party control, there are plenty WatermarkTextbox Controls available. I prefer the one from xceed: http://wpftoolkit.codeplex.com/wikipage?title=WatermarkTextBox

I wrote this behavior by myself some time ago, used an AdornerDecorator to lay over the TextBox, bound the IsFocused Property to my ViewModel and made a flag ShouldShowWatermark in which I bound the Visibility of the AdornerDecorator.

Upvotes: 0

Related Questions