如何将String转换为Int?

时间:2009-06-19 20:02:44

标签: c# .net string int type-conversion

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

我该怎么做?

33 个答案:

答案 0 :(得分:902)

试试这个:

int x = Int32.Parse(TextBoxD1.Text);

或更好:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

此外,由于Int32.TryParse返回bool,您可以使用其返回值来决定解析尝试的结果:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

如果您感到好奇,ParseTryParse之间的区别最好总结如下:

  

TryParse方法就像Parse一样   方法,除了TryParse方法   如果是,则不会抛出异常   转换失败。它消除了   需要使用异常处理来测试   对于事件中的FormatException   这是无效的,不可能的   成功解析。 - MSDN

答案 1 :(得分:46)

Convert.ToInt32( TextBoxD1.Text );

如果您确信文本框的内容是有效的int,请使用此选项。更安全的选择是

int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );

这将为您提供一些可以使用的默认值。 Int32.TryParse还返回一个布尔值,指示它是否能够解析,因此您甚至可以将其用作if语句的条件。

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}

答案 2 :(得分:31)

int.TryParse()

如果文本不是数字,则不会抛出。

答案 3 :(得分:17)

int myInt = int.Parse(TextBoxD1.Text)

另一种方式是:

bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

两者之间的区别在于,如果文本框中的值无法转换,第一个会抛出异常,而第二个则会返回false。

答案 4 :(得分:15)

您需要解析字符串,并且还需要确保它是真正的整数格式。

最简单的方法是:

int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
   // Code for if the string was valid
}
else
{
   // Code for if the string was invalid
}

答案 5 :(得分:10)

int x = 0;
int.TryParse(TextBoxD1.Text, out x);

TryParse语句返回一个布尔值,表示解析是否成功。如果成功,则解析的值将存储到第二个参数中。

有关详细信息,请参阅 Int32.TryParse Method (String, Int32)

答案 6 :(得分:9)

享受它......

int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);

答案 7 :(得分:8)

虽然这里已经有很多描述int.Parse的解决方案,但在所有答案中都缺少一些重要的解决方案。通常,数值的字符串表示因文化而异。数字字符串的元素(如货币符号,组(或千位)分隔符和小数分隔符)均因文化而异。

如果您想创建一种将字符串解析为整数的强大方法,那么考虑文化信息非常重要。如果您不这样做,则会使用current culture settings。这可能会给用户带来非常令人讨厌的惊喜 - 或者甚至更糟糕的是,如果您正在解析文件格式。如果您只是想要英语解析,最好通过指定要使用的文化设置来使其明确:

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

有关详细信息,请阅读CultureInfo,特别是MSDN上的NumberFormatInfo

答案 8 :(得分:8)

在char上使用Convert.ToInt32()时要小心!
它将返回角色的UTF-16代码!

如果您使用[i]索引编辑器仅在特定位置访问字符串,则会返回char而不是string

String input = "123678";

int x = Convert.ToInt32(input[4]);  // returns 55

int x = Convert.ToInt32(input[4].toString());  // returns 7

答案 9 :(得分:6)

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

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
}

答案 10 :(得分:6)

您可以编写自己的extesion方法

{
    "one": 1,
    "three": ​3
}

代码中的任何地方只需致电

public static class IntegerExtensions
{
    public static int ParseInt(this string value, int defaultValue = 0)
    {
        int parsedValue;
        if (int.TryParse(value, out parsedValue))
        {
            return parsedValue;
        }

        return defaultValue;
    }

    public static int? ParseNullableInt(this string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return null;
        }

        return value.ParseInt();
    }
}

在这个具体案例中

int myNumber = someString.ParseInt(); // returns value or 0
int age = someString.ParseInt(18); // with default value 18
int? userId = someString.ParseNullableInt(); // returns value or null

答案 11 :(得分:5)

您可以使用

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

{{1}}

答案 12 :(得分:4)

stringint的转换可以针对:intInt32Int64和其他反映.NET中整数数据类型的数据类型< / p>

以下示例显示了此转化:

此show(for info)数据适配器元素初始化为int值。同样可以直接完成,如

int xxiiqVal = Int32.Parse(strNabcd);

实施例

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

Link to see this demo

答案 13 :(得分:4)

您可以使用以下命令将字符串转换为C#:

转换类的功能,即Convert.ToInt16()Convert.ToInt32()Convert.ToInt64()或使用ParseTryParse函数。示例给出了here

答案 14 :(得分:4)

这样做

string x=TextBoxD1.Text;
int xi=Convert.ToInt32(x);

或者您可以使用

int xi=Int32.Parse(x);

参考Microsoft Developer Network for more information

答案 15 :(得分:4)

//May be quite some time ago but I just want throw in some line for any one who may still need it

int intValue;
string strValue = "2021";

try
{
    intValue = Convert.ToInt32(strValue);
}
catch
{
    //Default Value if conversion fails OR return specified error
    // Example 
    intValue = 2000;
}

答案 16 :(得分:3)

int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;

答案 17 :(得分:3)

您也可以使用extension method,因此它更具可读性(尽管每个人都已经习惯了常规的Parse函数)。

public static class StringExtensions
{
    /// <summary>
    /// Converts a string to int.
    /// </summary>
    /// <param name="value">The string to convert.</param>
    /// <returns>The converted integer.</returns>
    public static int ParseToInt32(this string value)
    {
        return int.Parse(value);
    }

    /// <summary>
    /// Checks whether the value is integer.
    /// </summary>
    /// <param name="value">The string to check.</param>
    /// <param name="result">The out int parameter.</param>
    /// <returns>true if the value is an integer; otherwise, false.</returns>
    public static bool TryParseToInt32(this string value, out int result)
    {
        return int.TryParse(value, out result);
    }
}

然后你可以这样称呼它:

  1. 如果您确定您的字符串是整数,例如“50”。

    int num = TextBoxD1.Text.ParseToInt32();
    
  2. 如果您不确定并希望防止崩溃。

    int num;
    if (TextBoxD1.Text.TryParseToInt32(out num))
    {
        //The parse was successful, the num has the parsed value.
    }
    
  3. 为了使它更具动态性,所以你也可以将它解析为double,float等,你可以做一个通用的扩展。

答案 18 :(得分:3)

如果没有TryParse或内置函数,你可以这样做

static int convertToInt(string a)
{
    int x=0;
    for (int i = 0; i < a.Length; i++)
        {
            int temp=a[i] - '0';
            if (temp!=0)
            {
                x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
            }              
        }
    return x ;
}

答案 19 :(得分:2)

我总是这样做的方式就像这样

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

这就是我会这样做的,我希望这会有所帮助。 (:

答案 20 :(得分:2)

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

答案 21 :(得分:2)

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

例如:

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

答案 22 :(得分:1)

如果您知道字符串是整数,请执行以下操作:

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

如果您不知道字符串是整数,请使用 TryParse 安全地进行操作。

C# 7.0 中,您可以使用 inline variable declaration

  • 如果解析成功 - value = 其解析值。
  • 如果解析失败 - 值 = 0。

代码:

if (int.TryParse(TextBoxD1.Text, out int value))
{
    // Parse succeed
}

缺点:

您无法区分 0 值和未解析的值。

答案 23 :(得分:1)

您可以在C#中将字符串转换为int许多不同类型的方法

第一个主要是使用:

string test = "123";
int x = Convert.ToInt16(test);

如果int值较高,则应使用int32类型。

第二个:

int x = int.Parse(text);

如果要进行错误检查,可以使用TryParse方法。在下面,我添加可为null的类型;

int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);

享受您的密码。...

答案 24 :(得分:1)

在C#v.7中,您可以使用内联输出参数,而无需其他变量声明:

int.TryParse(TextBoxD1.Text, out int x);

答案 25 :(得分:0)

此代码适用于Visual Studio 2010:

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

答案 26 :(得分:0)

虽然我同意使用 TryParse 方法,但很多人不喜欢使用 out 参数(包括我自己)。随着 C# 中添加了元组支持,另一种方法是创建一个扩展方法,将您使用 out 的次数限制为单个实例:

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# how to convert a string to int

答案 27 :(得分:0)

以上所有答案都不错,但作为参考,我们可以使用int.TryParse来将字符串转换为int,例如

// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
   Console.WriteLine(j);
else
   Console.WriteLine("String could not be parsed.");
// Output: -105

TryParse永远不会引发异常-即使输入无效且为null。在大多数程序上下文中,整体上最好使用int.Parse。

来源:How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)

答案 28 :(得分:0)

这对我有用:

@Bean
public HealthIndicator rabbitHealthIndicator() {
    return () -> Health.up().withDetail("version", "mock").build();
}

答案 29 :(得分:0)

方法1

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

方法2

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

方法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");
}

答案 30 :(得分:0)

如果您正在寻找漫长的道路,只需创建一个方法:

static int convertToInt(string a)
    {
        int x = 0;

        Char[] charArray = a.ToCharArray();
        int j = charArray.Length;

        for (int i = 0; i < charArray.Length; i++)
        {
            j--;
            int s = (int)Math.Pow(10, j);

            x += ((int)Char.GetNumericValue(charArray[i]) * s);
        }
        return x;
    }

答案 31 :(得分:0)

你可以试试这个,它会起作用:

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

变量TextBoxD1.Text中的字符串值将转换为Int32,并将存储在x中。

答案 32 :(得分:-3)

这可能对你有帮助; D

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        float Stukprijs;
        float Aantal;
        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            errorProvider2.Clear();
            if (float.TryParse(textBox1.Text, out Stukprijs))
            {
                if (float.TryParse(textBox2.Text, out Aantal))
                {
                    float Totaal = Stukprijs * Aantal;
                    string Output = Totaal.ToString();
                    textBox3.Text = Output;
                    if (Totaal >= 100)
                    {
                        float korting = Totaal - 100;
                        float korting2 = korting / 100 * 15;
                        string Output2 = korting2.ToString();
                        textBox4.Text = Output2;
                        if (korting2 >= 10)
                        {
                            textBox4.BackColor = Color.LightGreen;
                        }
                        else
                        {
                            textBox4.BackColor = SystemColors.Control;
                        }
                    }
                    else
                    {
                        textBox4.Text = "0";
                        textBox4.BackColor = SystemColors.Control;
                    }
                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }

            }
            else
            {
                errorProvider1.SetError(textBox1, "Bedrag plz!");
                if (float.TryParse(textBox2.Text, out Aantal))
                {

                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }
            }

        }

        private void BTNwissel_Click(object sender, EventArgs e)
        {
            //LL, LU, LR, LD.
            Color c = LL.BackColor;
            LL.BackColor = LU.BackColor;
            LU.BackColor = LR.BackColor;
            LR.BackColor = LD.BackColor;
            LD.BackColor = c;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
        }
    }
}
相关问题