Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleBuild a TextBox control that displays a prompt message when the user hasn't typed anything in Visual Basic .NET
DescriptionThis example shows how to build a TextBox control that displays a prompt message when the user hasn't typed anything in Visual Basic .NET.
KeywordsTextBox, PromptingTextBox, TextBox prompt, VB.NET, custom control
CategoriesControls, VB.NET
 
The control inherits from TextBox and adds a new Prompt property.
 
Private m_Prompt As String = "(Prompt)"
Public Property Prompt() As String
    Get
        Return m_Prompt
    End Get
    Set(ByVal Value As String)
        m_Prompt = Value
    End Set
End Property
 
When the control gets focus, it determines whether it contains the prompt text> If it does, the control blanks the text so the user can type something new.
 
<ToolboxBitmap(GetType(PromptingTextBox), _
    "PromptingTextBoxTool.bmp")> _
Private Sub PromptingTextBox_GotFocus(ByVal sender As _
    Object, ByVal e As System.EventArgs) Handles _
    MyBase.GotFocus
    If Me.Text = m_Prompt Then Me.Text = ""
    Me.ForeColor = Color.Black
End Sub
 
When the control loses focus, the control determines whether its text is blank. If the text is blank, the control displays its prompt and sets its foreground color to gray.
 
Private Sub PromptingTextBox_LostFocus(ByVal sender As _
    Object, ByVal e As System.EventArgs) Handles _
    MyBase.LostFocus
    If Me.Text.Length = 0 Then Me.Text = m_Prompt
    If Me.Text = m_Prompt Then
        Me.ForeColor = Color.Gray
    Else
        Me.ForeColor = Color.Black
    End If
End Sub
 
You're supposed to be able to set a TextBox's cue text by sending it the EM_SETCUEBANNER Message (see this MSDN article) but I have been unable make it work, possibly because I don't have visual styles set up properly or something. See also this Code Project article C# TextBox with Outlook 2007-style prompt. (And note that the prompting text box used on Microsoft's MSDN Web pages doesn't work very well either, at least in Firefox. It could be to do this really properly you would need to make more extensive modifications of the TextBox control.)
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated