我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
我总是这样做:
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.
}
}
}
我就是这样做的。
其他回答
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
int myInt = int.Parse(TextBoxD1.Text)
另一种方式是:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。
方法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");
}
您可以使用以下命令在C#中将字符串转换为int:
转换类的函数,即convert.ToInt16()、convert.ToInt32()、转换.ToInt64()或使用Parse和TryParse函数。这里给出了示例。
您可以在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);
享受您的代码。。。。