Adding placeholder text to textbox
Wouldn't that just be something like this:
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);
public void RemoveText(object sender, EventArgs e)
{
if (myTxtbx.Text == "Enter text here...")
{
myTxtbx.Text = "";
}
}
public void AddText(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
Thats just pseudocode but the concept is there.
How to add placeholder text to ToolStripTextBox?
ToolStripTextBox
hosts a ToolStripTextBoxControl
inside which is derived from TextBox
and you can access the the hosted control using its TextBox
or its Control
property. So you can write such code:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
[ToolboxBitmap(typeof(ToolStripTextBox))]
public class MyToolStripTextBox : ToolStripTextBox
{
private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg,
int wParam, string lParam);
public MyToolStripTextBox()
{
this.Control.HandleCreated += Control_HandleCreated;
}
private void Control_HandleCreated(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(cueBanner))
UpdateCueBanner();
}
string cueBanner;
public string CueBanner
{
get { return cueBanner; }
set
{
cueBanner = value;
UpdateCueBanner();
}
}
private void UpdateCueBanner()
{
SendMessage(this.Control.Handle, EM_SETCUEBANNER, 0, cueBanner);
}
}
Placeholder in TextBox in Window Forms using VB.NET
.NET 5.0+ or .NET Core 3.0+
Use TextBox.PlaceholderText property:
textBox1.PlaceholderText = "Enter your name"
.NET Framework
You can use either of the following approaches:
Sending
EM_SETCUEBANNER
to use the built-in placeholder feature of TextBox (Which just supports single-line text with gray placeholder text)Handling WM_PAINT message to show placeholder with custom color on both multi-line and single line TextBox (Which is the way that later is implemented in .NET Core)
Using EM_SETCUEBANNER
You can find a C# implementation of this approach here in this
post.
By sending EM_SETCUEBANNER
to a TextBox
, you can set the textual cue, or tip, that is displayed by the edit control to prompt the user for information.
Imports System
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Public Class MyTextBox
Inherits TextBox
Private Const EM_SETCUEBANNER As Integer = &H1501
<DllImport("user32.dll", CharSet:=CharSet.Auto)>
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, _
ByVal wParam As Integer, ByVal lParam As String) As Int32
End Function
Protected Overrides Sub OnHandleCreated(e As EventArgs)
MyBase.OnHandleCreated(e)
If Not String.IsNullOrEmpty(CueBanner) Then UpdateCueBanner()
End Sub
Private m_CueBanner As String
Public Property CueBanner As String
Get
Return m_CueBanner
End Get
Set(ByVal value As String)
m_CueBanner = value
UpdateCueBanner()
End Set
End Property
Private Sub UpdateCueBanner()
SendMessage(Me.Handle, EM_SETCUEBANNER, 0, CueBanner)
End Sub
End Class
Handling WM_PAINT
You can find a C# implementation of this approach here in this
post.
If you use EM_SETCUEBANNER, the hint always will be shown in a system default color. Also the hint will not be shown when the TextBox is MultiLine.
Using the painting solution, you can show the text with any color that you want. You also can show the watermark when the control is multi-line
Imports System.Drawing
Imports System.Windows.Forms
Public Class ExTextBox
Inherits TextBox
Private m_Hint As String
Public Property Hint As String
Get
Return m_Hint
End Get
Set(ByVal value As String)
m_Hint = value
Me.Invalidate()
End Set
End Property
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
If m.Msg = &HF Then
If Not Me.Focused AndAlso String.IsNullOrEmpty(Me.Text) _
AndAlso Not String.IsNullOrEmpty(Me.Hint) Then
Using g = Me.CreateGraphics()
TextRenderer.DrawText(g, Me.Hint, Me.Font, Me.ClientRectangle, _
SystemColors.GrayText, Me.BackColor, _
TextFormatFlags.Top Or TextFormatFlags.Left)
End Using
End If
End If
End Sub
End Class
How to Enter Placeholder Text Within Html.TextBoxFor in C# / MVC 4
Use an overload of TextBoxFor()
with an htmlAttributes
argument. This argument should be an anonymous object with all attributes you wish to assign to the input.
For example, if you want to set the placeholder
and class
attributes:
@Html.TextBoxFor( m => m.Email, new { placeholder = "Email", @class = "form-input" } )
How to set placeholder text in ASP.NET MVC TextBox
Its seems you are setting placeholder
text in the input fields in wrong way. Please do as follows:
<span class="SignUpText">
@Html.TextBoxFor(m => m.Name, new { placeholder="Name" })
</span>
<span class="SignUpText">
@Html.TextBoxFor(m => m.Email, new { placeholder="E-mail" })
</span>
Now you don't need to do anything with jQuery
.
Watermark / hint / placeholder text in TextBox?
This is a sample which demonstrates how to create a watermark textbox in WPF:
<Window x:Class="WaterMarkTextBoxDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WaterMarkTextBoxDemo"
Height="200" Width="400">
<Window.Resources>
<SolidColorBrush x:Key="brushWatermarkBackground" Color="White" />
<SolidColorBrush x:Key="brushWatermarkForeground" Color="LightSteelBlue" />
<SolidColorBrush x:Key="brushWatermarkBorder" Color="Indigo" />
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<local:TextInputToVisibilityConverter x:Key="TextInputToVisibilityConverter" />
<Style x:Key="EntryFieldStyle" TargetType="Grid" >
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="20,0" />
</Style>
</Window.Resources>
<Grid Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="{StaticResource brushWatermarkBackground}" Style="{StaticResource EntryFieldStyle}" >
<TextBlock Margin="5,2" Text="This prompt dissappears as you type..." Foreground="{StaticResource brushWatermarkForeground}"
Visibility="{Binding ElementName=txtUserEntry, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}" />
<TextBox Name="txtUserEntry" Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" />
</Grid>
<Grid Grid.Row="1" Background="{StaticResource brushWatermarkBackground}" Style="{StaticResource EntryFieldStyle}" >
<TextBlock Margin="5,2" Text="This dissappears as the control gets focus..." Foreground="{StaticResource brushWatermarkForeground}" >
<TextBlock.Visibility>
<MultiBinding Converter="{StaticResource TextInputToVisibilityConverter}">
<Binding ElementName="txtUserEntry2" Path="Text.IsEmpty" />
<Binding ElementName="txtUserEntry2" Path="IsFocused" />
</MultiBinding>
</TextBlock.Visibility>
</TextBlock>
<TextBox Name="txtUserEntry2" Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" />
</Grid>
</Grid>
</Window>
TextInputToVisibilityConverter is defined as:
using System;
using System.Windows.Data;
using System.Windows;
namespace WaterMarkTextBoxDemo
{
public class TextInputToVisibilityConverter : IMultiValueConverter
{
public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
// Always test MultiValueConverter inputs for non-null
// (to avoid crash bugs for views in the designer)
if (values[0] is bool && values[1] is bool)
{
bool hasText = !(bool)values[0];
bool hasFocus = (bool)values[1];
if (hasFocus || hasText)
return Visibility.Collapsed;
}
return Visibility.Visible;
}
public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture )
{
throw new NotImplementedException();
}
}
}
Note: This is not my code. I found it here, but I think this is the best approach.
Can't set placeholder on TextBox
Try this
<TextBox Name="search" Text="Search a user..." GotFocus="search_GotFocus"/>
private void search_GotFocus(object sender, RoutedEventArgs e)
{
search.Text = "";
}
Related Topics
Using Global Keyboard Hook (Wh_Keyboard_Ll) in Wpf/C#
Add Data Annotations to a Class Generated by Entity Framework
How to Get the Calling Method Name and Type Using Reflection
How to Get the Exif Data from a File Using C#
Get Last 10 Lines of Very Large Text File > 10Gb
If Statements Matching Multiple Values
How to Catch Exception in Task
Read SQL Table into C# Datatable
ASP.NET Calling Webmethod with Jquery Ajax "401 (Unauthorized)"
How to Get a Property Value Based on the Name
How to Automatically Filter Out Soft Deleted Entities with Entity Framework
Is It Bad to Not Unregister Event Handlers
Formatting Doubles for Output in C#
How to Force Garbage Collector to Run
ASP.NET MVC 5 Group of Radio Buttons
Regarding Usage of Task.Start() , Task.Run() and Task.Factory.Startnew()