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

我该怎么做?


当前回答

试试看:

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

或者更好:

int x = 0;

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

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

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

如果你很好奇,Parse和TryParse之间的区别最好总结如下:

TryParse方法类似于Parse方法,TryParse方法除外如果转换失败。它消除了需要使用异常处理来测试事件中的FormatExceptions无效,不能已成功解析。-世界末日

其他回答

int.TryParse()

如果文本不是数字,它不会抛出。

//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;
}

在C#v.7中,可以使用内联输出参数,而无需附加变量声明:

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

您可以借助parse方法将字符串转换为整数值。

Eg:

int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);

这样就可以了

string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);

或者你可以使用

int xi = Int32.Parse(x);

有关详细信息,请参阅Microsoft开发人员网络