How can I convert String to Int?

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

    Try this:

    int x = Int32.Parse(TextBoxD1.Text);
    

    or better yet:

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

    Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

    int x = 0;
    
    if (Int32.TryParse(TextBoxD1.Text, out x))
    {
        // you know that the parsing attempt
        // was successful
    }
    

    If you are curious, the difference between Parse and TryParse is best summed up like this:

    The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - MSDN

    0 讨论(0)
  • 2020-11-21 06:21
    int myInt = int.Parse(TextBoxD1.Text)
    

    Another way would be:

    bool isConvertible = false;
    int myInt = 0;
    
    isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
    

    The difference between the two is that the first one would throw an exception if the value in your textbox can't be converted, whereas the second one would just return false.

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

    This would do

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

    Or you can use

    int xi = Int32.Parse(x);
    

    Refer Microsoft Developer Network for more information

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

    If you're looking for the long way, just create your one method:

    static int convertToInt(string a)
        {
            int x = 0;
    
            Char[] charArray = a.ToCharArray();
            int j = charArray.Length;
    
            for (int i = 0; i < charArray.Length; i++)
            {
                j--;
                int s = (int)Math.Pow(10, j);
    
                x += ((int)Char.GetNumericValue(charArray[i]) * s);
            }
            return x;
        }
    
    0 讨论(0)
  • 2020-11-21 06:23

    Conversion of string to int can be done for: int, Int32, Int64 and other data types reflecting integer data types in .NET

    Below example shows this conversion:

    This show (for info) data adapter element initialized to int value. The same can be done directly like,

    int xxiiqVal = Int32.Parse(strNabcd);
    

    Ex.

    string strNii = "";
    UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
    

    Link to see this demo.

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

    You can use either,

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

    or

    int i = int.Parse(TextBoxD1.Text);
    
    0 讨论(0)
提交回复
热议问题