我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为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
}
其他回答
享受它。。。
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
//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;
}
上面的所有答案都很好,但为了提供信息,我们可以使用int.TryParse,例如,它可以安全地将字符串转换为int
// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
TryParse即使在无效输入和null时也不会抛出异常。在大多数程序上下文中,它总的来说比int.Parse更好。
来源:如何在C#中将字符串转换为int?(Int.Parse和Int.TryParse之间存在差异)
这样就可以了
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
或者你可以使用
int xi = Int32.Parse(x);
有关详细信息,请参阅Microsoft开发人员网络
可以为int、Int32、Int64和其他反映.NET中整数数据类型的数据类型将字符串转换为int
以下示例显示了此转换:
这显示了初始化为int值的(for info)数据适配器元素。同样可以直接进行,
int xxiiqVal = Int32.Parse(strNabcd);
Ex.
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
链接以查看此演示。