我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
int.TryParse()
如果文本不是数字,它不会抛出。
其他回答
虽然我同意使用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 parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
// Code for if the string was valid
}
else
{
// Code for if the string was invalid
}
//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许多不同类型的方法#
第一种主要使用:
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);
享受您的代码。。。。
int i = Convert.ToInt32(TextBoxD1.Text);