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

我该怎么做?


当前回答

对字符使用Convert.ToInt32()时要小心!它将返回字符的UTF-16代码!

如果使用[i]索引运算符仅在某个位置访问字符串,它将返回一个字符而不是字符串!

String input = "123678";
                    ^
                    |
int indexOfSeven =  4;

int x = Convert.ToInt32(input[indexOfSeven]);             // Returns 55

int x = Convert.ToInt32(input[indexOfSeven].toString());  // Returns 7

其他回答

//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函数)。

public static class StringExtensions
{
    /// <summary>
    /// Converts a string to int.
    /// </summary>
    /// <param name="value">The string to convert.</param>
    /// <returns>The converted integer.</returns>
    public static int ParseToInt32(this string value)
    {
        return int.Parse(value);
    }

    /// <summary>
    /// Checks whether the value is integer.
    /// </summary>
    /// <param name="value">The string to check.</param>
    /// <param name="result">The out int parameter.</param>
    /// <returns>true if the value is an integer; otherwise, false.</returns>
    public static bool TryParseToInt32(this string value, out int result)
    {
        return int.TryParse(value, out result);
    }
}

然后你可以这样称呼它:

如果您确定字符串是整数,如“50”。int num=TextBoxD1.Text.ParseToInt32();如果您不确定并希望防止崩溃。整数;if(TextBoxD1.Text.TryParseToInt32(out num)){//解析成功,num具有解析的值。}

为了使其更动态,以便您也可以将其解析为double、float等,您可以创建一个通用扩展。

Convert.ToInt32( TextBoxD1.Text );

如果您确信文本框的内容是有效的int,请使用此选项

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

这将为您提供一些可以使用的默认值。Int32.TryParse还返回一个布尔值,指示它是否能够解析,因此您甚至可以将其用作if语句的条件。

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}

上面的所有答案都很好,但为了提供信息,我们可以使用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之间存在差异)

享受它。。。

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