我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为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");
}
其他回答
//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#中将字符串转换为int:
转换类的函数,即convert.ToInt16()、convert.ToInt32()、转换.ToInt64()或使用Parse和TryParse函数。这里给出了示例。
int i = Convert.ToInt32(TextBoxD1.Text);
这样就可以了
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
或者你可以使用
int xi = Int32.Parse(x);
有关详细信息,请参阅Microsoft开发人员网络
int myInt = int.Parse(TextBoxD1.Text)
另一种方式是:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。