0

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.

  • The product name must be there always while there is no text in the TextBox
  • I also want that if I click on the TextBox for the second time I don't lose what I've already entered.

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.

Ghasem
  • 14,455
  • 21
  • 138
  • 171
Ahsan Hussain
  • 952
  • 4
  • 21
  • 42

5 Answers5

1

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
har07
  • 88,338
  • 12
  • 84
  • 137
1

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";  
    } 
}
Yael
  • 1,566
  • 3
  • 18
  • 25
Jack Frost
  • 277
  • 2
  • 3
  • 12
0

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.

Herm
  • 2,956
  • 19
  • 32
0

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.

Community
  • 1
  • 1
Krishna
  • 1,956
  • 13
  • 25
0

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();)

Zuabros
  • 252
  • 1
  • 5