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

其他回答

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

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

虽然我同意使用TryParse方法,但很多人不喜欢使用out参数(包括我自己)。在C#中添加了元组支持后,另一种方法是创建一个扩展方法,该方法将限制您使用单个实例的次数:

public static class StringExtensions
{
    public static (int result, bool canParse) TryParse(this string s)
    {
        int res;
        var valid = int.TryParse(s, out res);
        return (result: res, canParse: valid);
    }
}

(来源:C#如何将字符串转换为int)

您可以使用,

int i = Convert.ToInt32(TextBoxD1.Text);

or

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

可以为int、Int32、Int64和其他反映.NET中整数数据类型的数据类型将字符串转换为int

以下示例显示了此转换:

这显示了初始化为int值的(for info)数据适配器元素。同样可以直接进行,

int xxiiqVal = Int32.Parse(strNabcd);

Ex.

string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );

链接以查看此演示。

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