How can I convert String to Int?

2018-12-31 01:54发布

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?

28条回答
浅入江南
2楼-- · 2018-12-31 02:28

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 statment says if the string not a number display an error elce now you will have an intager.
        }
    }
}

this is how i would do it, i hope this helps. (:

查看更多
时光乱了年华
3楼-- · 2018-12-31 02:29

METHOD 1

int  TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
    Console.WriteLine("String not Convertable to an Integer");
}

METHOD 2

int TheAnswer2 = 0;
try {
    TheAnswer2 = Int32.Parse("42");
}
catch {
    Console.WriteLine("String not Convertable to an Integer");
}

METHOD 3

int TheAnswer3 = 0;
try {
    TheAnswer3 = Int32.Parse("42");
}
catch (FormatException) {
    Console.WriteLine("String not in the correct format for an Integer");
}
catch (ArgumentNullException) {
    Console.WriteLine("String is null");
}
catch (OverflowException) {
    Console.WriteLine("String represents a number less than"
                      + "MinValue or greater than MaxValue");
}
查看更多
低头抚发
4楼-- · 2018-12-31 02:30

Conversion of string to int can be done for: int, Int32, Int64 and other data types reflecting integer data types in .NET

Below example shows this conversion:

This show (for info) data adapter element initialized to int value. The same can be done directly like,

int xxiiqVal = Int32.Parse(strNabcd);

Ex.

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

Link to see this demo.

查看更多
泪湿衣
5楼-- · 2018-12-31 02:31
int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;
查看更多
人气声优
6楼-- · 2018-12-31 02:31

This code works for me in Visual Studio 2010:

int someValue = Convert.ToInt32(TextBoxD1.Text);
查看更多
路过你的时光
7楼-- · 2018-12-31 02:32

You can convert a string to int in C# using:

Functions of convert class i.e. Convert.ToInt16(), Convert.ToInt32(), Convert.ToInt64() or by using Parse and TryParse Functions. Examples are given here.

查看更多
登录 后发表回答