ASP.NET AJAX TextBox Watermark Control

Waqas Anwar
30 June 2009
26756 Views

ASP.NET AJAX TextBox Watermark Extender control can be attached to an ASP.NET TextBox control to make it work as watermark TextBox. If TextBox is empty, it will display a message to the user with a custom CSS style. It user will type something in the TextBox that initial message will disappear. The main purpose of TextBox is to provide extra information to the user about the data required in the TextBox. In this tutorial I will show you how you can use ASP.NET AJAX TextBox Watermark Control in your ASP.NET Projects.

ASP.NET AJAX Watermark Extender Control

To start this tutorial you need to create a blank ASP.NET page that have an instance of AJAX ScriptManager control on top. This control is required to use any AJAX related feature in ASP.NET page and to enable partial page rendering.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
In the Web Form, Add two TextBox Controls along with two TextBoxWatermarkExtender controls as shown in the following markup.
Name:

<asp:TextBox ID="TextBox1" runat="server" CssClass="nonwatermarked" />

<ajax:TextBoxWatermarkExtender
   ID="TextBoxWatermarkExtender1"
   runat="server"
   Enabled="True"
   TargetControlID="TextBox1"
   WatermarkCssClass="watermarked"
   WatermarkText="Enter Name Here"
>
</ajax:TextBoxWatermarkExtender>

<br />

Phone:

<asp:TextBox ID="TextBox2" runat="server" CssClass="nonwatermarked" />

<ajax:TextBoxWatermarkExtender
   ID="TextBoxWatermarkExtender2"
   runat="server"
   Enabled="True"
   TargetControlID="TextBox2"
   WatermarkCssClass="watermarked"
   WatermarkText="Enter Phone Here"
>
</ajax:TextBoxWatermarkExtender>

<br /> <br />

<asp:Button ID="Button1" runat="server" Text="Submit " />

The TextBoxWatermarkExtender control is very straight forward and it has only few properties to make it work. TargetControlID property needs the ID of a target TextBox control on which you want to display watermark text. WatermarkText property needs the text you want to display when the TextBox is empty. WatermarkCssClass needs the name of the CSS class that has some styles defined for the TextBox such as background color or border styles. Note TextBox also has CssClass property to attach a CSS class to it for styling but WatermarkCssClass only apply styles when TextBox is empty. Following are the two CSS classes used in the above example:
.watermarked
{
   background-color: #E1E1E1;
   border: solid 1px #808080;
   padding: 2px;
}

.nonwatermarked
{
   border: solid 1px #808080;
   padding: 2px;
}

You can add the above CSS classes into an external CSS file and can attach the CSS file with ASP.NET page using link tag.
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />