How can I convert String to Int?

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

    You need to parse the string, and you also need to ensure that it is truly in the format of an integer.

    The easiest way is this:

    int parsedInt = 0;
    if (int.TryParse(TextBoxD1.Text, out parsedInt))
    {
       // Code for if the string was valid
    }
    else
    {
       // Code for if the string was invalid
    }
    
    0 讨论(0)
  • 2020-11-21 06:16

    You can convert a string to int in C# using:

    Functions of convert class i.e. Convert.ToInt16(), Convert.ToInt32(), Convert.ToInt64() or by using Parse and TryParse Functions. Examples are given here.

    0 讨论(0)
  • 2020-11-21 06:18

    You can convert string to int many different type methods in C#

    First one is mostly use :

    string test = "123";
    int x = Convert.ToInt16(test);
    

    if int value is higher you should use int32 type.

    Second one:

    int x = int.Parse(text);
    

    if you want to error check, you can use TryParse method. In below I add nullable type;

    int i=0;
    Int32.TryParse(text, out i) ? i : (int?)null);
    

    Enjoy your codes....

    0 讨论(0)
  • 2020-11-21 06:19

    This code works for me in Visual Studio 2010:

    int someValue = Convert.ToInt32(TextBoxD1.Text);
    
    0 讨论(0)
  • 2020-11-21 06:20
    int x = 0;
    int.TryParse(TextBoxD1.Text, out x);
    

    The TryParse statement returns a boolean representing whether the parse has succeeded or not. If it succeeded, the parsed value is stored into the second parameter.

    See Int32.TryParse Method (String, Int32) for more detailed information.

    0 讨论(0)
  • 2020-11-21 06:20

    You can do like below without TryParse or inbuilt functions:

    static int convertToInt(string a)
    {
        int x = 0;
        for (int i = 0; i < a.Length; i++)
        {
            int temp = a[i] - '0';
            if (temp != 0)
            {
                x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
            }
        }
        return x;
    }
    
    0 讨论(0)
提交回复
热议问题