Text Box Watermark

BronwenWeeGo.jpgWanted a watermark on a text box similar to local.live.com and came across Deobrat’s post which i found really useful.

I’ve converted the code to c# and used the textbox.ClientID instead of ID as we are using anthem etc ID doesn’t work for us.

Here’s the code:

using System;
using System;
using System.Text;
using System.Web.UI.WebControls;

namespace Helper
{
    public static class WatermarkHelper
    {
        public static void ApplyWaterMarkToTextBox(ref TextBox textBox, string waterMarkText, 
                                            string waterMarkStyle, string normalStyle)
        {
            textBox.Attributes.Add("OnFocus",
                                   "javascript:js_waterMark_Focus('" + textBox.ClientID + "', '" +
                                   waterMarkText.Replace("'", "\'") + "','" + waterMarkStyle + "', '" + normalStyle +
                                   "')");
            textBox.Attributes.Add("OnBlur",
                                   "javascript:js_waterMark_Blur('" + textBox.ClientID + "', '" +
                                   waterMarkText.Replace("'", "\'") + "','" + waterMarkStyle + "', '" + normalStyle +
                                   "')");
            textBox.Text = waterMarkText;
            textBox.CssClass = waterMarkStyle;
            if (!textBox.Page.ClientScript.IsClientScriptBlockRegistered("WaterMarkScript"))
            {
                StringBuilder scriptBuilder = new StringBuilder();

                scriptBuilder.Append(@"" + Environment.NewLine);
                textBox.Page.ClientScript.RegisterClientScriptBlock(textBox.Page.GetType(), "WaterMarkScript",
                                                                    scriptBuilder.ToString(), false);
            }
        }
    }
}