asp.net 中 string 转换成 int 的问题?

来源:百度知道 编辑:UC知道 时间:2024/05/17 03:36:27
我在页面加载的时候简单的写了一段代码:

protected void Page_Load(object sender, EventArgs e)
{
string a = this.TextBox1.Text;
string b = this.TextBox2.Text;

int c = Convert.ToInt32(a) + Convert.ToInt32(b);
this.TextBox3.Text = c.ToString();
}

运行的时候怎么总是说输入字符串的格式不正确,是什么原因啊。谢谢~~

那就是你的TextBox1或TextBox2的内容里有非数字的东西
代码改一下:
protected void Page_Load(object sender, EventArgs e)
{
string a = this.TextBox1.Text.Trim();
string b = this.TextBox2.Text.Trim();
try{
int c = Convert.ToInt32(a) + Convert.ToInt32(b);
this.TextBox3.Text = c.ToString();
}
catch(Exception){
this.TextBox3.Text = "输入的不是数字";
}
}

用TryParse 更省事

int c = 0;
if(int.TryParse(a, out c)){
//完成了转换 值保存在c中
}else{
//非数值字符串
}