How can I convert String to Int?

后端 未结 30 2143
情歌与酒
情歌与酒 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: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
    {
        /// 
        /// Converts a string to int.
        /// 
        /// The string to convert.
        /// The converted integer.
        public static int ParseToInt32(this string value)
        {
            return int.Parse(value);
        }
    
        /// 
        /// Checks whether the value is integer.
        /// 
        /// The string to check.
        /// The out int parameter.
        /// true if the value is an integer; otherwise, false.
        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.

提交回复
热议问题