我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
上面的所有答案都很好,但为了提供信息,我们可以使用int.TryParse,例如,它可以安全地将字符串转换为int
// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
TryParse即使在无效输入和null时也不会抛出异常。在大多数程序上下文中,它总的来说比int.Parse更好。
来源:如何在C#中将字符串转换为int?(Int.Parse和Int.TryParse之间存在差异)
其他回答
Convert.ToInt32( TextBoxD1.Text );
如果您确信文本框的内容是有效的int,请使用此选项
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );
这将为您提供一些可以使用的默认值。Int32.TryParse还返回一个布尔值,指示它是否能够解析,因此您甚至可以将其用作if语句的条件。
if( Int32.TryParse( TextBoxD1.Text, out val ){
DoSomething(..);
} else {
HandleBadInput(..);
}
试试看:
int x = Int32.Parse(TextBoxD1.Text);
或者更好:
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
此外,由于Int32.TryParse返回bool,您可以使用其返回值来决定解析尝试的结果:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
如果你很好奇,Parse和TryParse之间的区别最好总结如下:
TryParse方法类似于Parse方法,TryParse方法除外如果转换失败。它消除了需要使用异常处理来测试事件中的FormatExceptions无效,不能已成功解析。-世界末日
您可以在C中将字符串转换为int许多不同类型的方法#
第一种主要使用:
string test = "123";
int x = Convert.ToInt16(test);
如果int值更高,则应使用int32类型。
第二个:
int x = int.Parse(text);
如果要进行错误检查,可以使用TryParse方法。在下面我添加了可为null的类型;
int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);
享受您的代码。。。。
int.TryParse()
如果文本不是数字,它不会抛出。
如果您正在寻找长远的方法,只需创建一个方法:
static int convertToInt(string a)
{
int x = 0;
Char[] charArray = a.ToCharArray();
int j = charArray.Length;
for (int i = 0; i < charArray.Length; i++)
{
j--;
int s = (int)Math.Pow(10, j);
x += ((int)Char.GetNumericValue(charArray[i]) * s);
}
return x;
}