我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
如TryParse文档中所述,TryPars()返回一个布尔值,表示找到了一个有效的数字:
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// Put val in database
}
else
{
// Handle the case that the string doesn't contain a valid number
}
其他回答
如TryParse文档中所述,TryPars()返回一个布尔值,表示找到了一个有效的数字:
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// Put val in database
}
else
{
// Handle the case that the string doesn't contain a valid number
}
对字符使用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
您可以编写自己的扩展方法
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
代码中的任何地方都可以调用
int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null
在这个具体的例子中
int yourValue = TextBoxD1.Text.ParseInt();
int myInt = int.Parse(TextBoxD1.Text)
另一种方式是:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;