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

我该怎么做?


当前回答

享受它。。。

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方法,但很多人不喜欢使用out参数(包括我自己)。在C#中添加了元组支持后,另一种方法是创建一个扩展方法,该方法将限制您使用单个实例的次数:

public static class StringExtensions
{
    public static (int result, bool canParse) TryParse(this string s)
    {
        int res;
        var valid = int.TryParse(s, out res);
        return (result: res, canParse: valid);
    }
}

(来源:C#如何将字符串转换为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.Parse的解决方案,但所有答案中都缺少一些重要的内容。通常,数值的字符串表示因区域性而异。数字字符串的元素,如货币符号、组(或千)分隔符和小数分隔符,都因文化而异。

如果您想创建一种将字符串解析为整数的健壮方法,那么考虑区域性信息非常重要。如果没有,将使用当前的区域性设置。这可能会给用户一个非常可怕的惊喜——甚至更糟糕的是,如果你正在解析文件格式。如果您只想进行英语解析,最好通过指定要使用的区域性设置,使其明确:

var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
    // use result...
}

有关更多信息,请阅读CultureInfo,特别是MSDN上的NumberFormatInfo。