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

我该怎么做?


当前回答

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

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

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

其他回答

试试看:

int x = Int32.Parse(TextBoxD1.Text);

或者更好:

int x = 0;

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

此外,由于Int32.TryParse返回bool,您可以使用其返回值来决定解析尝试的结果:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

如果你很好奇,Parse和TryParse之间的区别最好总结如下:

TryParse方法类似于Parse方法,TryParse方法除外如果转换失败。它消除了需要使用异常处理来测试事件中的FormatExceptions无效,不能已成功解析。-世界末日

对字符使用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
int.TryParse()

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

您也可以使用扩展方法,这样它会更可读(尽管每个人都已经习惯了常规的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等,您可以创建一个通用扩展。

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

最简单的方法是:

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
}