How can I convert String to Int?

后端 未结 30 2156
情歌与酒
情歌与酒 2020-11-21 05:35

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.

How can I do this?

30条回答
  •  礼貌的吻别
    2020-11-21 06:27

    The way I always do this is like this:

    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.
            }
        }
    }
    

    This is how I would do it.

提交回复
热议问题