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

我该怎么做?


当前回答

可以为int、Int32、Int64和其他反映.NET中整数数据类型的数据类型将字符串转换为int

以下示例显示了此转换:

这显示了初始化为int值的(for info)数据适配器元素。同样可以直接进行,

int xxiiqVal = Int32.Parse(strNabcd);

Ex.

string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );

链接以查看此演示。

其他回答

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

Eg:

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

您可以使用,

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

or

int i = int.Parse(TextBoxD1.Text);

虽然我同意使用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)

我总是这样做:

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;