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

我该怎么做?


当前回答

您可以使用,

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

or

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

其他回答

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

Eg:

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

虽然我同意使用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)

方法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");
}
int myInt = int.Parse(TextBoxD1.Text)

另一种方式是:

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。

您可以在C中将字符串转换为int许多不同类型的方法#

第一种主要使用:

string test = "123";
int x = Convert.ToInt16(test);

如果int值更高,则应使用int32类型。

第二个:

int x = int.Parse(text);

如果要进行错误检查,可以使用TryParse方法。在下面我添加了可为null的类型;

int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);

享受您的代码。。。。