首页 新闻 会员 周边 捐助

c# 类型转换

0
悬赏园豆:10 [已解决问题] 解决于 2013-08-01 21:04

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)
    {

    }
}

zhangpengpeng的主页 zhangpengpeng | 初学一级 | 园豆:114
提问于:2013-04-16 17:23
< >
分享
最佳答案
0

  int n = Convert.Int32(TextBox1.Text.ToString());

收获园豆:10
珍是唯一 | 初学一级 |园豆:4 | 2013-04-20 10:42
其他回答(2)
0

int.Parse对于转换不了的字符串会抛出异常。

可以考虑使用int.TryParse来转换,当返回true时,标识能转换,再做你后面的逻辑

滴答的雨 | 园豆:3660 (老鸟四级) | 2013-04-16 17:29
0

        /// <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的时候,做成扩展方法更好。

呆呆蚁 | 园豆:231 (菜鸟二级) | 2013-04-16 18:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册