从字符串转换为int [英] conversion from string to int
本文介绍了从字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
dd.Id = Convert.ToInt32(txtid.Text);
如果我在Internet Explorer中执行该表单,它是执行。但如果输入上面给出的字段的值,则显示如下错误
输入字符串的格式不正确。
推荐答案
这意味着您输入的String
不是有效的整数
。
您应该使用 int.TryParse [ ^ ]。
这不会引发异常。相反,它会尝试解析String
,否则它将不会做任何事情。
所以,喜欢。 ..
That means theString
you are entering is not a validinteger
.
You should go with int.TryParse[^].
This will not throw you exception. Rather it will try to parse theString
, else it will not do anything.
So, do like...
int num = 0;
bool res = int.TryParse(txtid.Text, out num);
if (!res)
{
// String is not a number.
}
看起来像你的' txtid.Text'是可以为空的值(或为空)。您无法将空值转换为Int32。您需要确保每个值都不为空(或不为空)。
在转换前检查以下检查。
It looks like your 'txtid.Text' is a nullable value (or empty).You cannot convert a null value to an Int32. You need to ensure that each value is not null (or not empty).
Check below checking before the conversion.
if (!string.IsNullOrEmpty(txtid.Text))
{
dd.Id = Convert.ToInt32(txtid.Text);
}
您可能在文本末尾添加了space
,
总是更好地trim
值TextBox
而不是Convert.ToInt32
你可以使用TryParse
Might be you have addedspace
at the end of the text,
Its always better totrim
the value ofTextBox
Instead ofConvert.ToInt32
you can useTryParse
int value = 0;
bool isInteger = int.TryParse(btnshow.Text.Trim(), out value);
if (isInteger)
{
// converted successfully
// value contains the data which u entered in text box.
}
else
{
// invalid entry, but it will not throw error.
// here the value will be 0
}
这篇关于从字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文