Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

TextBox with Placeholder

0.00/5 (No votes)
2 May 2018 3  
Extended TextBox with placeholder

Introduction

In many cases, a TextBox with an easy Placeholder property would be very helpful especially when you want the user to filter a ListView or ListBox by search terms.

So, I never found a really good one. I know there exists a very easy method with only one SendMessage method, but I don't like it because the placeholder is hard to differentiate with the actually typed text and I don't like these message things very much, too many things can go wrong.

Now I created my own control and my destination is that it is very easy to use.

Using the Code

Add the PlaceholderTextBox.cs to your project and build it. You can add it with the designer now.

The difference to the usual TextBox is it that there are three new properties:

  • PlaceholderText: It's not hard to guess what this property does. It defines the Placeholder text which will get displayed if the TextBox is empty.
  • IsPlaceholderActive: Through this property, you can always check if the textbox shows the placeholder or real text at the moment.

PlaceholderText is accessible with the designer, IsPlaceholderActive is not!

Besides, there is the new method Reset(). This will return the TextBox to the start state.

The Text property is not accessible with the designer. That's to keep the standard. The placeholder should always be seen before you type any text in the TextBox.

Points of Interest

It's a very well written code. I recommend you read it, there are many comments and maybe you have a suggestion.

I hope you like my control and when you have any suggestions or have found a bug, please let me know!

History

v1.6

  • "Select all" in Windows default context menu does not select the placeholder anymore
  • TextLength returns 0 if placeholder is active
  • Minor code improvements

v1.5

  • Fixed behavior with pressing Ctrl+A while placeholder is active
  • MaxLength working now
  • Fixed crashes if setting Text programmatically

v1.4

v1.3

  • Fixed bug: Font can be changed now - Thanks to Member 11133660
  • Improved internal logic
  • Removed IsItalics
  • Renamed PlaceholderInsideChanged to PlaceholderActiveChanged

v1.2

  • Improved internal logic
  • Removed sealed
  • Added Placeholder category to designer for better overview
  • Fixed some comments

v1.1

  • Added PlaceholderInsideChanged event
  • Fixed bug that new MouseDownEvents never occur
  • Prevents user to go through placeholder with arrow keys

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here