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

我该怎么做?


当前回答

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

其他回答

方法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");
}
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(..);
}

对字符使用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
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;

这样就可以了

string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);

或者你可以使用

int xi = Int32.Parse(x);

有关详细信息,请参阅Microsoft开发人员网络