我有一个TextBoxD1.Text
,我想把它转换为int
来存储在数据库中。
我怎样才能做到这一点?
试试这个。
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方法 如果转换失败,不会抛出一个异常。 转换失败时不会抛出异常。它消除了 需要使用异常处理来测试 事件中的FormatException。 s是无效的,不能被 成功解析。- MSDN
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(..);
}
当在char上使用Convert.ToInt32()时要小心! <br>.它将返回字符的[UTF-16]()代码! 它将返回字符的UTF-16代码!
如果你只在特定的位置使用[i]
索引操作符访问字符串,它将返回一个char
而不是string
!
String input = "123678";
int x = Convert.ToInt32(input[4]); // returns 55
int x = Convert.ToInt32(input[4].toString()); // returns 7
虽然这里已经有很多解决方案描述了int.Parse
,但在所有的答案中都缺少一些重要的东西。
通常情况下,数值的字符串表示方式因文化而异。
数值字符串的元素,如货币符号、组(或千位)分隔符和小数分隔符都因文化而不同。
如果你想创建一个健壮的方法来解析字符串到整数,因此考虑文化信息是很重要的。 如果你不考虑,就会使用 [当前文化设置][1] 。 这可能会给用户一个非常讨厌的惊喜--或者更糟糕,如果你正在解析文件格式的话。 如果你只是想要英文解析,最好是通过指定要使用的文化设置来明确。
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
// use result...
}
更多信息,请阅读CultureInfo,特别是MSDN上的[NumberFormatInfo][2]。
[1]: https://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture(v=vs.110).aspx [2]: https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo(v=vs.110).aspx
你可以写自己的扩展方法。
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();
正如[TryParse文档][1]中解释的那样,TryParse()返回一个布尔值,表示找到了一个有效的数字。
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// put val in database
}
else
{
// handle the case that the string doesn't contain a valid number
}
可以将string
转换为int
。
int
、Int32
、Int64
和其他反映.NET中整数数据类型的数据类型。
下面的例子显示了这种转换。
这个显示(用于信息)数据适配器元素初始化为int值。 同样的也可以直接做。
int xxiiqVal = Int32.Parse(strNabcd);
前。
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
[链接查看该演示][1].
[1]:
//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;
}
这将做
string x=TextBoxD1.Text;
int xi=Convert.ToInt32(x);
或者您可以使用
int xi=Int32.Parse(x);
更多信息请参考【微软开发者网】[1] 。
你可以在C#中使用转换类的函数将一个字符串转换为int。
convert类的函数,即
Convert.ToInt16()
、Convert.ToInt32()
、Convert.ToInt64()
或者使用Parse
和TryParse
函数。
例子在[这里][1]中给出。
你也可以使用扩展方法,这样会更容易读懂(虽然大家已经习惯了常规的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);
}
}
然后你就可以这样称呼它。
int num = TextBoxD1.Text.ParseToInt32()。
int num.Text.ParseToInt32(); 3.如果你不确定,又想防止崩溃。 如果(TextBoxD1.Text.TryParseToInt32(out num)) { //解析成功,num有解析后的值。 }
为了让它更动态,让你也能解析成double、float等,你可以做一个通用扩展。
1:
你可以在不使用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 ;
}