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

我该怎么做?


当前回答

享受它。。。

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

其他回答

您可以在C中将字符串转换为int许多不同类型的方法#

第一种主要使用:

string test = "123";
int x = Convert.ToInt16(test);

如果int值更高,则应使用int32类型。

第二个:

int x = int.Parse(text);

如果要进行错误检查,可以使用TryParse方法。在下面我添加了可为null的类型;

int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);

享受您的代码。。。。

享受它。。。

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

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

您需要解析字符串,还需要确保它确实是整数格式。

最简单的方法是:

int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
   // Code for if the string was valid
}
else
{
   // Code for if the string was invalid
}
//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;
}