我有一个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");
}
其他回答
我总是这样做:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace example_string_to_int
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
// This turns the text in text box 1 into a string
int b;
if (!int.TryParse(a, out b))
{
MessageBox.Show("This is not a number");
}
else
{
textBox2.Text = a+" is a number" ;
}
// Then this 'if' statement says if the string is not a number, display an error, else now you will have an integer.
}
}
}
我就是这样做的。
在C#v.7中,可以使用内联输出参数,而无需附加变量声明:
int.TryParse(TextBoxD1.Text, out int x);
试试看:
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方法除外如果转换失败。它消除了需要使用异常处理来测试事件中的FormatExceptions无效,不能已成功解析。-世界末日
虽然这里已经有很多描述int.Parse的解决方案,但所有答案中都缺少一些重要的内容。通常,数值的字符串表示因区域性而异。数字字符串的元素,如货币符号、组(或千)分隔符和小数分隔符,都因文化而异。
如果您想创建一种将字符串解析为整数的健壮方法,那么考虑区域性信息非常重要。如果没有,将使用当前的区域性设置。这可能会给用户一个非常可怕的惊喜——甚至更糟糕的是,如果你正在解析文件格式。如果您只想进行英语解析,最好通过指定要使用的区域性设置,使其明确:
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
// use result...
}
有关更多信息,请阅读CultureInfo,特别是MSDN上的NumberFormatInfo。
您可以尝试以下方法。它将起作用:
int x = Convert.ToInt32(TextBoxD1.Text);
变量TextBoxD1.Text中的字符串值将转换为Int32并存储在x中。