我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。

我该怎么做?


当前回答

在C#v.7中,可以使用内联输出参数,而无需附加变量声明:

int.TryParse(TextBoxD1.Text, out int x);

其他回答

方法1

int  TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
    Console.WriteLine("String not Convertable to an Integer");
}

方法2

int TheAnswer2 = 0;
try {
    TheAnswer2 = Int32.Parse("42");
}
catch {
    Console.WriteLine("String not Convertable to an Integer");
}

方法3

int TheAnswer3 = 0;
try {
    TheAnswer3 = Int32.Parse("42");
}
catch (FormatException) {
    Console.WriteLine("String not in the correct format for an Integer");
}
catch (ArgumentNullException) {
    Console.WriteLine("String is null");
}
catch (OverflowException) {
    Console.WriteLine("String represents a number less than"
                      + "MinValue or greater than MaxValue");
}
int myInt = int.Parse(TextBoxD1.Text)

另一种方式是:

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。

int.TryParse()

如果文本不是数字,它不会抛出。

int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;

如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
}