基于项目需要,针对ASP.net服务器控件TextBox进行改造,使其增加字符串输入提示功能,在控件获得焦点时,与普通的服务器端 TextBox 控件相同,支持数据输入。当控件失去焦点并且文本框内容为空时,显示预定义的提示文本。用户输入“预定义的提示文本”为文本内容时, 默认文本框Text值为空字符串。
[DefaultProperty("Text")]
[ToolboxData("<{0}:TextBox runat=server></{0}:TextBox>")]
public class TextBox : System.Web.UI.WebControls.TextBox
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
[Browsable(true)]
public string Tip
{
get
{
String s = (String)ViewState["Tip"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Tip"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public override string Text
{
get
{
if (base.Text.ToLower() == Tip.ToLower())
return string.Empty;
return base.Text;
}
set
{
base.Text = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
this.Attributes.Add("tip",Tip);
this.Attributes.Add("onblur",
"if(this.value==''){this.style.color='#C1C1C1';this.value='"+Tip+"';};");
this.Attributes.Add("onfocus",
"if(this.value=='"+Tip+"'){this.style.color='#000000';this.value='';};");
if (string.IsNullOrEmpty(base.Text.Trim()))
{
this.Attributes.Add("value", this.Tip);
this.Attributes.Add("style", "color:#C1C1C1");
}
base.Render(writer);
}
}
本文出自 “学习成就梦想” 博客,请务必保留此出处http://qijinchao.blog.51cto.com/1140455/263627