How can I convert String to Int?

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

    Be careful when using Convert.ToInt32() on a char! It will return the UTF-16 code of the character!

    If you access the string only in a certain position using the [i] indexing operator, it will return a char and not a string!

    String input = "123678";
                        ^
                        |
    int indexOfSeven =  4;
    
    int x = Convert.ToInt32(input[indexOfSeven]);             // Returns 55
    
    int x = Convert.ToInt32(input[indexOfSeven].toString());  // Returns 7
    
    0 讨论(0)
  • 2020-11-21 06:29

    In C# v.7 you could use an inline out parameter, without an additional variable declaration:

    int.TryParse(TextBoxD1.Text, out int x);
    
    0 讨论(0)
  • 2020-11-21 06:31
    int.TryParse()
    

    It won't throw if the text is not numeric.

    0 讨论(0)
  • 2020-11-21 06:32
    int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
    
    0 讨论(0)
  • 2020-11-21 06:34

    You can write your own extension method

    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();
        }
    }
    

    And wherever in code just call

    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
    

    In this concrete case

    int yourValue = TextBoxD1.Text.ParseInt();
    
    0 讨论(0)
  • 2020-11-21 06:36

    You can try the following. It will work:

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

    The string value in the variable TextBoxD1.Text will be converted into Int32 and will be stored in x.

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