我有一个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;
}

其他回答

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

Eg:

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

如果您正在寻找长远的方法,只需创建一个方法:

static int convertToInt(string a)
{
    int x = 0;
        
    Char[] charArray = a.ToCharArray();
    int j = charArray.Length;

    for (int i = 0; i < charArray.Length; i++)
    {
        j--;
        int s = (int)Math.Pow(10, j);

        x += ((int)Char.GetNumericValue(charArray[i]) * s);
    }
    return x;
}

这样就可以了

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

或者你可以使用

int xi = Int32.Parse(x);

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

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

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

您可以在没有TryParse或内置函数的情况下执行以下操作:

static int convertToInt(string a)
{
    int x = 0;
    for (int i = 0; i < a.Length; i++)
    {
        int temp = a[i] - '0';
        if (temp != 0)
        {
            x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
        }
    }
    return x;
}