Tag Archives: ASP

Hint text in ASP.NET TextBox controls

More and more often these days, you see hint text in a textbox control on a web form.  You know the kind of thing – “user name” or “password” appearing in silver text within an input control.  Well, I had to implement that functionality today and it is surprisingly easy to achieve.

The first thing you need to do is create your TextBox control on the page.  Once you’ve done that, add the following method to your codebehind file.

private void SetTextBoxHints(TextBox textBox, string defaultText)
{
textBox.Attributes.Add(“onfocus”, “clearText(this,'” + defaultText + “‘)”);
textBox.Attributes.Add(“onblur”, “resetText(this,'” + defaultText + “‘)”);
if (textBox.Text == “”)
{
textBox.Text = defaultText;
textBox.ForeColor = System.Drawing.Color.Silver;
}
else if (textBox.Text == defaultText)
{
textBox.ForeColor = System.Drawing.Color.Silver;
}
else
{
textBox.ForeColor = System.Drawing.Color.Black;

}

 Next, you’ll need to add the javascript to the page/user control to look after the dynamic changes in content/colour. 

<script type="text/javascript" language="javascript">
<!--
function clearText(ctrl,defaultText) {
if(ctrl.value == defaultText)
ctrl.value = ""
ctrl.style.color = "#000000";
}
function resetText(ctrl,defaultText) {
if(ctrl.value == "")
{
 ctrl.value = defaultText
 ctrl.style.color = "#C0C0C0";
}
}
// -->
</script>

Then, you need to call the setup method for each Textbox you want to control.

SetTextBoxHints(myControl, "the text you want to show as default...");

And that, as they say, is that. Enjoy.