How can I convert String to Int?

后端 未结 30 2262
情歌与酒
情歌与酒 2020-11-21 05:35

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.

How can I do this?

30条回答
  •  故里飘歌
    2020-11-21 06:14

    METHOD 1

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

    METHOD 2

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

    METHOD 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");
    }
    

提交回复
热议问题