How can I convert String to Int?

2018-12-31 01:54发布

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?

28条回答
低头抚发
2楼-- · 2018-12-31 02:21

You can use either,

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

or

int i =int.Parse(TextBoxD1.Text);
查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 02:23

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
}
查看更多
情到深处是孤独
4楼-- · 2018-12-31 02:23

As explained in the TryParse documentation, TryParse() returns a boolean which indicates that a valid number was found:

bool success = Int32.TryParse(TextBoxD1.Text, out val);

if (success)
{
// put val in database
}
else
{
// handle the case that the string doesn't contain a valid number
}
查看更多
余欢
5楼-- · 2018-12-31 02:24

Be carefull when using Convert.ToInt32() on a char!
It will return the UTF-16 Code of the character!

If you access the string only in a certain position using the [i] indexing operator it will return a char and not a string!

String input = "123678";

int x = Convert.ToInt32(input[4]);  // returns 55

int x = Convert.ToInt32(input[4].toString());  // returns 7
查看更多
零度萤火
6楼-- · 2018-12-31 02:25

Enjoy it...

int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
查看更多
余生无你
7楼-- · 2018-12-31 02:27
int.TryParse()

It won't throw if the text is not numeric.

查看更多
登录 后发表回答