获取错误“输入字符串的格式不正确” [英] Getting error "Input string was not in a correct format"

查看:70
本文介绍了获取错误“输入字符串的格式不正确”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从以下代码中,



From the following code,

string strid  = txtId.Text;
int id = Convert.ToInt32(strid);





我收到这样的消息

输入字符串格式不正确

我该怎么办?



I was getting a message like this
"Input string was not in a correct format"
what should I do?

推荐答案

试试这个,



Try this,

string strid  = txtId.Text;
int id=0;
Int32.TryParse(strid, out id);





使用上面的代码,你不会得到错误,你将在id变量中获得转换后的值。如果strid不在格式良好的输入中,你' ll在id中得到0作为值。: - )



Using above code, you'll not get the error, and you'll get the converted value in id variable.If strid is not in well formed input, you'll get 0 in id as a value.:-)


txtId.Text中的任何内容都不能解释为int。您无法控制文本框中的内容,因此请使用 int.TryParse ,以便您可以处理当输入不是int时。
Whatever is in txtId.Text can't be interpreted as an int. You can't control what is in a textbox so use int.TryParse instead so that you can handle when the input is not an int.






检查txtId.Text是否有值。如果txtId.Text是(空),那么它如何转换为整数?



所以,你的代码应如下:



Hi,

Check if txtId.Text has value. If txtId.Text is ""(empty), then how it convert to integer?

so, your code should be as follow:

string strid = txtId.Text;

if(strid != "")
{
    int id = Convert.ToInt32(strid);
}


这篇关于获取错误“输入字符串的格式不正确”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆