我如何将字符串转换为INT? [英] How can I convert String to Int?

查看:302
本文介绍了我如何将字符串转换为INT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TextBoxD1.Text

和我想要将其转换为'诠释',将其存储在数据库中。我怎样才能做到这一点?

and I want to convert it to 'int' to store it in a database. How can I do this?

推荐答案

试试这个:

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

或者更好的:

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

此外,由于 Int32.TryParse 返回布尔可以将其返回值来做出解析尝试的结果作出决定:

Also, since Int32.TryParse returns a bool you can 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
}

如果你是好奇,解析的TryParse 是最好的总结是这样的区别:

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

本的TryParse方法类似于解析   方法,不同的方法的TryParse   不会抛出异常,如果   转换失败。它消除了   需要使用异常处理来测试   在事件出现FormatException   即s无效,并且不能   成功解析。 - MSDN

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

这篇关于我如何将字符串转换为INT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆