我有一个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.
}
}
}
我就是这样做的。
其他回答
在C#v.7中,可以使用内联输出参数,而无需附加变量声明:
int.TryParse(TextBoxD1.Text, out int x);
享受它。。。
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
这样就可以了
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
或者你可以使用
int xi = Int32.Parse(x);
有关详细信息,请参阅Microsoft开发人员网络
您可以借助parse方法将字符串转换为整数值。
Eg:
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;