我有一个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之间存在差异)
其他回答
如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
}
int i = Convert.ToInt32(TextBoxD1.Text);
您可以编写自己的扩展方法
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 x = Convert.ToInt32(TextBoxD1.Text);
变量TextBoxD1.Text中的字符串值将转换为Int32并存储在x中。
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;