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:43

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

查看更多
深知你不懂我心
3楼-- · 2018-12-31 02:43
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.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 02:43
//May be quite some time ago but I just want throw in some line for any one who may still need it

int intValue;
string strValue = "2021";

try
{
    intValue = Convert.ToInt32(strValue);
}
catch
{
    //Default Value if conversion fails OR return specified error
    // Example 
    intValue = 2000;
}
查看更多
还给你的自由
5楼-- · 2018-12-31 02:44

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

查看更多
登录 后发表回答