How can I convert String to Int?

后端 未结 30 2782
情歌与酒
情歌与酒 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: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();
    

提交回复
热议问题