using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Chapter4_2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Title = "输入一个偶数";
TextBox1.Focus();
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = true;
int n = int.Parse(TextBox1.Text.ToString());//字符转换对吗?
if (TextBox1.Text == " ")
{
args.IsValid = false ;
// CustomValidator1.Text = " ";
CustomValidator1.Text = "必须输入! ";
CustomValidator1.ErrorMessage = "验证不通过!";
//ValidationSummary1.HeaderText = "验证不通过";
}
else
{
if ( n % 2 == 0)
{
args.IsValid = false;
CustomValidator1.Text = " 验证通过!";
CustomValidator1.ErrorMessage = "验证通过!";
if (2 <= n && 1000 >= n)
{
args.IsValid = false ;
CustomValidator1.Text = " ";
CustomValidator1.ErrorMessage = "验证通过!";
}
else
{
args.IsValid = false;
CustomValidator1.Text = "超出范围2~1000! ";
CustomValidator1.ErrorMessage = "验证失败!";
}
}
else
{
args.IsValid = false ;
CustomValidator1.Text = "必须输入偶数! ";
CustomValidator1.ErrorMessage = "验证失败!";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
int n = Convert.Int32(TextBox1.Text.ToString());
int.Parse对于转换不了的字符串会抛出异常。
可以考虑使用int.TryParse来转换,当返回true时,标识能转换,再做你后面的逻辑
/// <summary>
/// 此方法慎用
/// 将指定的值转换为有符号整数
/// 此方法不会抛出异常,转换失败将返回defValue
/// </summary>
/// <param name="str">指定对象</param>
/// <param name="defValue">缺省值</param>
/// <returns>int</returns>
public int ToInt(object value, int defValue)
{
int result;
if (!int.TryParse(value.ToString(), out result))
{
result = defValue;
}
return result;
}
这样就OK了,如果是framework版本不低于3.5的时候,做成扩展方法更好。