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

我该怎么做?


当前回答

int i = Convert.ToInt32(TextBoxD1.Text);

其他回答

我总是这样做:

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 i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);

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

Eg:

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

如TryParse文档中所述,TryPars()返回一个布尔值,表示找到了一个有效的数字:

bool success = Int32.TryParse(TextBoxD1.Text, out val);

if (success)
{
    // Put val in database
}
else
{
    // Handle the case that the string doesn't contain a valid number
}

对字符使用Convert.ToInt32()时要小心!它将返回字符的UTF-16代码!

如果使用[i]索引运算符仅在某个位置访问字符串,它将返回一个字符而不是字符串!

String input = "123678";
                    ^
                    |
int indexOfSeven =  4;

int x = Convert.ToInt32(input[indexOfSeven]);             // Returns 55

int x = Convert.ToInt32(input[indexOfSeven].toString());  // Returns 7