我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
其他回答
您可以在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);
享受您的代码。。。。
对字符使用Convert.ToInt32()时要小心!它将返回字符的UTF-16代码!
如果使用[i]索引运算符仅在某个位置访问字符串,它将返回一个字符而不是字符串!
String input = "123678";
^
|
int indexOfSeven = 4;
int x = Convert.ToInt32(input[indexOfSeven]); // Returns 55
int x = Convert.ToInt32(input[indexOfSeven].toString()); // Returns 7
您可以在没有TryParse或内置函数的情况下执行以下操作:
static int convertToInt(string a)
{
int x = 0;
for (int i = 0; i < a.Length; i++)
{
int temp = a[i] - '0';
if (temp != 0)
{
x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
}
}
return x;
}
//May be quite some time ago but I just want throw in some line for any one who may still need it
int intValue;
string strValue = "2021";
try
{
intValue = Convert.ToInt32(strValue);
}
catch
{
//Default Value if conversion fails OR return specified error
// Example
intValue = 2000;
}
试试看:
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无效,不能已成功解析。-世界末日