[英]How to i get my textbox to only allow numbers 1-14?
This is what i have so far, but I am obviously getting an error. 到目前为止,这是我所拥有的,但是显然我遇到了错误。
try
{
dblNights = Convert.ToDouble(txtNights.Text);
if (dblNights > 1 && 14)
{
}
else
{
string script = "alert(\"Number of Nights Must be between 1 and 14!\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
txtNights.Focus();
}
}//End Try
catch
{
string script = "alert(\"Number of Nights Must be an Integer!\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
txtNights.Focus();
}//End Catch
I am not quite sure what to do to make show an error box if numbers besides 1-14 are entered. 如果输入的数字不是1-14,我不太确定如何显示错误框。 Everything else is working, just not that.
其他所有东西都在起作用,但事实并非如此。 What am I doing wrong?
我究竟做错了什么?
Thank you. 谢谢。
Problem : You are not properly using the Logical AND
operator. 问题:您没有正确使用
Logical AND
运算符。
This: 这个:
if (dblNights > 1 && 14)
{
}
Must be: 一定是:
if (dblNights >= 1 && dblNights <= 14)
{
/*valid range some thing here*/
}
EDIT: as suggested by Eric Lippert in comments i would like to show you usage of TryParse
. 编辑:正如埃里克·利珀特(Eric Lippert)在评论中所建议的,我想向您展示
TryParse
用法。
if you use double.TryParse()
you can eliminate the Exceptions
which may occur with invalid data.because double.TryParse()
method would return the Boolean
value true
if the conversion is successful otherwise it returns false
so that you could avoid try catch
blocks. 如果使用
double.TryParse()
,则可以消除无效数据可能发生的Exceptions
因为如果转换成功, double.TryParse()
方法将返回Boolean
值true
,否则返回false
这样就可以避免try catch
块。
Try This: 尝试这个:
double dblNights;
if (double.TryParse(txtNights.Text, out dblNights))
{
//conversion is successfull
}
else
{
//conversion is Failed
}
I would have used a RangeValidator 我本来会使用RangeValidator
http://www.w3schools.com/aspnet/control_rangevalidator.asp http://www.w3schools.com/aspnet/control_rangevalidator.asp
Save's you the trouble of reinventing the wheel. 省去了您重新发明轮子的麻烦。 You can set it's Type property to Integer or Double and not have to worry about parsing values just to validate them.
您可以将其Type属性设置为Integer或Double,而不必担心只是为了验证它们而解析值。
您可以使用html 5
<input type="number" min="1" max="14" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.