我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。

我该怎么做?


当前回答

int myInt = int.Parse(TextBoxD1.Text)

另一种方式是:

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。

其他回答

int x = 0;
int.TryParse(TextBoxD1.Text, out x);

TryParse语句返回一个布尔值,表示解析是否成功。如果成功,解析的值将存储到第二个参数中。

有关详细信息,请参阅Int32.TryParse方法(字符串,Int32)。

我总是这样做:

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#中将字符串转换为int:

转换类的函数,即convert.ToInt16()、convert.ToInt32()、转换.ToInt64()或使用Parse和TryParse函数。这里给出了示例。

int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;

您可以借助parse方法将字符串转换为整数值。

Eg:

int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);