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

我该怎么做?


当前回答

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

其他回答

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

TryParse语句返回一个布尔值,表示解析是否成功。如果成功,解析的值将存储到第二个参数中。

有关详细信息,请参阅Int32.TryParse方法(字符串,Int32)。

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

您可以使用以下命令在C#中将字符串转换为int:

转换类的函数,即convert.ToInt16()、convert.ToInt32()、转换.ToInt64()或使用Parse和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;
}

享受它。。。

int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);