我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
您可以借助parse方法将字符串转换为整数值。
Eg:
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
其他回答
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(..);
}
您可以在没有TryParse或内置函数的情况下执行以下操作:
static int convertToInt(string a)
{
int x = 0;
for (int i = 0; i < a.Length; i++)
{
int temp = a[i] - '0';
if (temp != 0)
{
x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
}
}
return x;
}
您可以编写自己的扩展方法
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
代码中的任何地方都可以调用
int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null
在这个具体的例子中
int yourValue = TextBoxD1.Text.ParseInt();
您可以使用,
int i = Convert.ToInt32(TextBoxD1.Text);
or
int i = int.Parse(TextBoxD1.Text);
您可以在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);
享受您的代码。。。。