asp.net 控件学习:如何制作带验证的TextBox
时间:2011-04-11 来源:不够牛B的肖邦
代码如下:自定义控件一定要重写Render方法
[DefaultProperty("Text"), ToolboxData("<{0}:TextBox runat=server></{0}:TextBox>"), Designer("System.Web.UI.Design.WebControls.PreviewControlDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class TextBox : System.Web.UI.WebControls.TextBox
{
protected RequiredFieldValidator CanBeBullRFV = new RequiredFieldValidator();
public TextBox():base()
{
this.Attributes.Add("onfocus", "this.className='txt_focus';");
this.Attributes.Add("onblur", "this.className='txt';");
base.CssClass = "txt";
}
protected override void CreateChildControls()
{
if (!CanBeNull)
{
CanBeBullRFV.Display = ValidatorDisplay.Dynamic;
CanBeBullRFV.ControlToValidate = this.ID;
CanBeBullRFV.ErrorMessage = "<font color=red>不能为空!</font>";
this.Controls.AddAt(0, CanBeBullRFV);
}
}
public bool CanBeNull
{
get
{
return ViewState["CanBeNull"] == null ? true : Convert.ToBoolean(ViewState["CanBeNull"]);
}
set { ViewState["CanBeNull"] = value; }
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
base.RenderChildren(writer);
}
}
前台使用:加上下面两句就行了
<%@ Register Assembly="HRM.Control" Namespace="HRM.Control" TagPrefix="cc1" %>
<cc1:TextBox ID="TextBox1" runat="server" CanBeNull="false"></cc1:TextBox>
相关阅读 更多 +