基於項目需要,針對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