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

我该怎么做?


当前回答

如果您知道字符串是整数,请执行以下操作:

int value = int.Parse(TextBoxD1.Text);

如果您不知道字符串是整数,请使用TryParse安全地执行。

在C#7.0中,可以使用内联变量声明。

如果解析成功-value=其解析值。如果解析失败-值=0。

代码:

if (int.TryParse(TextBoxD1.Text, out int value))
{
    // Parse succeed
}

缺点:

无法区分0值和未分析的值。

其他回答

您可以在没有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;
}

方法1

int  TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
    Console.WriteLine("String not Convertable to an Integer");
}

方法2

int TheAnswer2 = 0;
try {
    TheAnswer2 = Int32.Parse("42");
}
catch {
    Console.WriteLine("String not Convertable to an Integer");
}

方法3

int TheAnswer3 = 0;
try {
    TheAnswer3 = Int32.Parse("42");
}
catch (FormatException) {
    Console.WriteLine("String not in the correct format for an Integer");
}
catch (ArgumentNullException) {
    Console.WriteLine("String is null");
}
catch (OverflowException) {
    Console.WriteLine("String represents a number less than"
                      + "MinValue or greater than MaxValue");
}

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

Eg:

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

上面的所有答案都很好,但为了提供信息,我们可以使用int.TryParse,例如,它可以安全地将字符串转换为int

// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
   Console.WriteLine(j);
else
   Console.WriteLine("String could not be parsed.");
// Output: -105

TryParse即使在无效输入和null时也不会抛出异常。在大多数程序上下文中,它总的来说比int.Parse更好。

来源:如何在C#中将字符串转换为int?(Int.Parse和Int.TryParse之间存在差异)

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

转换类的函数,即convert.ToInt16()、convert.ToInt32()、转换.ToInt64()或使用Parse和TryParse函数。这里给出了示例。