How can I convert String to Int?

后端 未结 30 2261
情歌与酒
情歌与酒 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 06:13

    All above answers are good but for information, we can use int.TryParse which is safe to convert string to int , example

    // TryParse returns true if the conversion succeeded
    // and stores the result in j.
    int j;
    if (Int32.TryParse("-105", out j))
       Console.WriteLine(j);
    else
       Console.WriteLine("String could not be parsed.");
    // Output: -105
    

    TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.

    Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)

提交回复
热议问题