下面以创建一个只允许输入整型数据的textbox控件(IntegerTextBox),并且使该控件具有只允许输入的数据必须在一定的范围内,但我们仍然需要考虑是否允许空值,所以,象上面一样,需要添加一个属性
在上面我们创建的基本的textbox控件的基础上,我们仅仅需要继承该控件,然后覆盖Validate函数和添加一些新的属性
private int _minValue = Int32.MinValue;
private int _maxValue = Int32.MaxValue;
public int MinValue {
get { return _minValue; }
set {
_minValue = value;
if (_minValue > _maxValue) {
int swap = _minValue;
_minValue = _maxValue;
_maxValue = swap;
}
}
}
public int MaxValue {
get { return _maxValue; }
set {
_maxValue = value;
if (_minValue > _maxValue) {
int swap = _minValue;
_minValue = _maxValue;
_maxValue = swap;
}
}
}
然后,我们扩充该Validate函数,并把编译它为本地代码
public override void Validate() {
this.IsValid = true;
bool isBlank = (this.Text.Trim() == "");
if (isBlank) {
if (!AllowBlank) {
this.ErrorMessage = String.Format("'{0}' " +
"cannot be blank.", this.FriendlyName);
this.IsValid = false;
}
} else {
try {
_value = Int32.Parse(this.Text);
if (_value < this.MinValue) {
this.ErrorMessage = String.Format("'{0}' cannot " +
"be less than {1}",
this.FriendlyName, this.MinValue);
this.IsValid = false;
}
if (_value > this.MaxValue) {
this.ErrorMessage = String.Format("'{0}' " +
"cannot be more than {1}",
this.FriendlyName, this.MinValue);
this.IsValid = false;
}
} catch {
this.ErrorMessage = String.Format("'{0}' " +
"is not a valid integer.", this.FriendlyName);
this.IsValid = false;
}
}
}
public int Value {
get { return _value; }
set {
_value = value;
this.Text = _value.ToString();
}
}
结论
要写就那么多了,现在我们还可以在这个类的基础上创建诸如要求只能输入符合一定时间格式和货币格式,下面我们举一个例子以说明怎么样使用我们创建的控件
在此以前我们要实现同样的功能需要写以下的代码:
<asp:TextBox id="Number" runat="server"/>
<asp:RequiredFieldValidator id="RequiredFieldValidator2"
ControlToValidate="Number"
Text="'Number' cannot be blank." runat="server"/>
<asp:RangeValidator id="Range1" ControlToValidate="Number"
MinimumValue="0" MaximumValue="100"
Type="Integer" Text="The value must be from 0 to 100!"
runat="server"/>
而现在,我们仅仅需一句:
MyControls:IntegerText id="Number"
FriendlyName="Number" MinValue="0" MaxValue="100"
AllowBlank="false" runat="server">
如果您对本文有任何疑问或者建议,请到讨论区发表您的意见:
>>
论坛入口 <<
上一篇:
.Net在SqlServer中的图片存取技术 下一篇:
在两个ASP.NET页面之间传递值
【文章评论】
【收藏本文】
【推荐好友】
【打印本文】
【我要投稿】 【论坛讨论】