Monday, March 23, 2015

How to add a placeholder in a Windows Forms textbox

Recently, working on UniversalIDE, my current open source project, I encountered the necessity of adding a placeholder in a TextBox control. UniversalIDE is still based on the Windows Forms user interface instead of the newer WPF one, and the Windows Forms TextBox control doesn't provide natively the placeholder feature. So I decided to write a very simple class which extends the TextBox control and has a PlaceHolderText property that allows to set a placeholder to show when the field is empty.

Here is the Visual Basic .NET code:

Public Class PlaceHolderTextBox
    Inherits TextBox

    Dim isPlaceHolder As Boolean = True
    Dim _placeHolderText As String
    Public Property PlaceHolderText As String
            Return _placeHolderText
        End Get
        Set(value As String)
            _placeHolderText = value
        End Set
    End Property

    Private Sub setPlaceholder() Handles Me.LostFocus 'when the control loses focus, the placeholder is shown
        If Me.Text = "" Then
            Me.Text = PlaceHolderText
            Me.ForeColor = Color.Gray
            Me.Font = New Font(Me.Font, FontStyle.Italic)
            isPlaceHolder = True
        End If
    End Sub

    Private Sub removePlaceHolder() Handles Me.GotFocus 'when the control is focused, the placeholder is removed

        If isPlaceHolder Then
            Me.Text = ""
            Me.ForeColor = System.Drawing.SystemColors.WindowText
            Me.Font = New Font(Me.Font, FontStyle.Regular)
            isPlaceHolder = False
        End If
    End Sub
End Class

You can easily integrate this class in any VB.NET application; simply copy the code in a .vb file (a best practice is to name the file as the class, so PlaceHolderTextBox.vb); then, compile the project, and the PlaceHolderTextBox control will become available as the other normal controls in the Visual Studio Toolbox when you open a Windows Form in Design Mode. Simply drag the control on a form and set the PlaceHolderText property (this can be done from the Properties window, as in the screenshot below, or from code) and you'll get a TextBox with your placeholder.

The PlaceHolderText property in Visual Studio
Example of a PlaceHolderTextBox
Since the code is very simple, it can easily be customized (for example, you may want to change the font color or remove the italic decoration), and you can also translate it into C# if you have a basic knowledge of Visual Basic .NET and C#.