How can I convert String to Int?

后端 未结 30 2203
情歌与酒
情歌与酒 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:11

    Enjoy it...

    int i = 0;
    string s = "123";
    i =int.Parse(s);
    i = Convert.ToInt32(s);
    
    0 讨论(0)
  • 2020-11-21 06:12
    //May be quite some time ago but I just want throw in some line for any one who may still need it
    
    int intValue;
    string strValue = "2021";
    
    try
    {
        intValue = Convert.ToInt32(strValue);
    }
    catch
    {
        //Default Value if conversion fails OR return specified error
        // Example 
        intValue = 2000;
    }
    
    0 讨论(0)
  • 2020-11-21 06:13

    All above answers are good but for information, we can use int.TryParse which is safe to convert string to int , example

    // 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 never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.

    Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)

    0 讨论(0)
  • 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");
    }
    
    0 讨论(0)
  • 2020-11-21 06:15
    Convert.ToInt32( TextBoxD1.Text );
    

    Use this if you feel confident that the contents of the text box is a valid int. A safer option is

    int val = 0;
    Int32.TryParse( TextBoxD1.Text, out val );
    

    This will provide you with some default value you can use. Int32.TryParse also returns a Boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an if statement.

    if( Int32.TryParse( TextBoxD1.Text, out val ){
      DoSomething(..);
    } else {
      HandleBadInput(..);
    }
    
    0 讨论(0)
  • 2020-11-21 06:15

    You also may use an extension method, so it will be more readable (although everybody is already used to the regular Parse functions).

    public static class StringExtensions
    {
        /// <summary>
        /// Converts a string to int.
        /// </summary>
        /// <param name="value">The string to convert.</param>
        /// <returns>The converted integer.</returns>
        public static int ParseToInt32(this string value)
        {
            return int.Parse(value);
        }
    
        /// <summary>
        /// Checks whether the value is integer.
        /// </summary>
        /// <param name="value">The string to check.</param>
        /// <param name="result">The out int parameter.</param>
        /// <returns>true if the value is an integer; otherwise, false.</returns>
        public static bool TryParseToInt32(this string value, out int result)
        {
            return int.TryParse(value, out result);
        }
    }
    

    And then you can call it that way:

    1. If you are sure that your string is an integer, like "50".

      int num = TextBoxD1.Text.ParseToInt32();
      
    2. If you are not sure and want to prevent crashes.

      int num;
      if (TextBoxD1.Text.TryParseToInt32(out num))
      {
          //The parse was successful, the num has the parsed value.
      }
      

    To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.

    0 讨论(0)
提交回复
热议问题