如何让我的文本框只允许1-14号?

Tra*_*vis 0 c# asp.net

这是我到目前为止,但我显然是一个错误.

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
Run Code Online (Sandbox Code Playgroud)

如果输入1-14之外的数字,我不太清楚如何显示错误框.其他一切都在起作用,就是这样.我究竟做错了什么?

谢谢.

Sud*_*udi 6

问题:您没有正确使用Logical AND运营商.

这个:

       if (dblNights > 1 && 14)
        {

        }
Run Code Online (Sandbox Code Playgroud)

一定是:

       if (dblNights >= 1 && dblNights <= 14)
        {
             /*valid range some thing here*/
        }
Run Code Online (Sandbox Code Playgroud)

编辑:正如Eric Lippert在评论中所建议的,我想向您展示使用TryParse.

如果您使用,double.TryParse()您可以消除Exceptions无效数据可能发生的情况.因为如果转换成功,double.TryParse()方法将返回Booleantrue,否则返回false以便您可以避免try catch阻塞.

试试这个:

        double dblNights;
        if (double.TryParse(txtNights.Text, out dblNights))
        {
            //conversion is successfull
        }
        else
        {
            //conversion is Failed
        }
Run Code Online (Sandbox Code Playgroud)