Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c# - 如何将String转换为Int?(How can I convert String to Int?)

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.

(我有一个TextBoxD1.Text ,我想将其转换为一个int以将其存储在数据库中。)

How can I do this?

(我怎样才能做到这一点?)

  ask by turki2009 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(同样,由于Int32.TryParse返回bool您可以使用其返回值来决定解析尝试的结果:)

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:

(如果您很好奇,最好将ParseTryParse之间的区别总结如下:)

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.

(TryParse方法类似于Parse方法,但是如果转换失败,TryParse方法不会引发异常。)

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.

(如果s无效且无法成功解析,则无需使用异常处理来测试FormatException。)

- MSDN

(-MSDN)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...