745

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

我怎样才能做到这一点?

4

34 回答 34

1185

试试这个:

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

或者更好:

int x = 0;

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

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

int x = 0;

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

Parse如果您好奇,最好将和之间的区别TryParse总结如下:

TryParse 方法与 Parse 方法类似,只是 TryParse 方法在转换失败时不会抛出异常。它消除了在 s 无效且无法成功解析的情况下使用异常处理来测试 FormatException 的需要。- MSDN

于 2009-06-19T20:04:50.673 回答
69
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(..);
}
于 2009-06-19T20:04:41.533 回答
39
int.TryParse()

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

于 2009-06-19T20:05:05.697 回答
23
int myInt = int.Parse(TextBoxD1.Text)

另一种方法是:

bool isConvertible = false;
int myInt = 0;

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

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

于 2009-06-19T20:08:03.320 回答
16

您需要解析字符串,还需要确保它确实是整数格式。

最简单的方法是这样的:

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
}
于 2009-06-19T20:06:36.910 回答
16

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

如果您使用索引运算符仅在特定位置访问字符串[i],它将返回 achar而不是 a string

String input = "123678";
                    ^
                    |
int indexOfSeven =  4;

int x = Convert.ToInt32(input[indexOfSeven]);             // Returns 55

int x = Convert.ToInt32(input[indexOfSeven].toString());  // Returns 7
于 2016-02-03T16:42:37.777 回答
12
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

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

有关更多详细信息,请参阅Int32.TryParse 方法(字符串,Int32)

于 2009-06-19T20:11:51.563 回答
12

好好享受...

int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
于 2015-04-11T07:25:34.637 回答
11

虽然这里已经有很多描述 的解决方案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

于 2015-07-06T11:33:17.640 回答
9

您可以编写自己的扩展方法

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

在这个具体案例中

int yourValue = TextBoxD1.Text.ParseInt();
于 2016-02-05T13:05:09.297 回答
9
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
于 2017-01-27T21:40:50.347 回答
8

正如TryParse 文档中所解释的,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
}
于 2009-06-19T20:10:41.347 回答
6

可以为:、、和其他反映 .NET 中整数数据类型的数据类型转换stringintintInt32Int64

下面的示例显示了这种转换:

这显示(用于信息)数据适配器元素初始化为 int 值。可以直接做同样的事情,

int xxiiqVal = Int32.Parse(strNabcd);

前任。

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

链接以查看此演示

于 2016-05-16T06:01:41.650 回答
5

你可以使用任何一个,

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

或者

int i = int.Parse(TextBoxD1.Text);
于 2015-09-07T09:42:18.227 回答
5
//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;
}
于 2017-01-03T19:36:56.503 回答
5

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

第一个主要是使用:

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

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

第二个:

int x = int.Parse(text);

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

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

享受你的代码......

于 2020-10-09T10:35:41.373 回答
4
int i = Convert.ToInt32(TextBoxD1.Text);
于 2010-05-29T06:39:55.107 回答
4

您也可以使用扩展方法,因此它会更具可读性(尽管每个人都已经习惯了常规的 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.
    }
    

为了使其更具动态性,因此您也可以将其解析为 double、float 等,您可以进行通用扩展。

于 2013-10-25T16:11:51.487 回答
4

这会做

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

或者你可以使用

int xi = Int32.Parse(x);

有关详细信息,请参阅Microsoft 开发人员网络

于 2017-07-03T06:27:19.130 回答
4

您可以在没有 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;
}
于 2017-09-15T02:34:46.630 回答
4

您可以使用以下方法将字符串转换为 C# 中的 int:

转换类的函数,即Convert.ToInt16(), Convert.ToInt32()Convert.ToInt64()或使用ParseandTryParse函数。这里给出了例子。

于 2018-05-11T06:16:13.587 回答
3

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

例如:

int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
于 2018-10-17T06:03:12.723 回答
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' statement says if the string is not a number, display an error, else now you will have an integer.
        }
    }
}

我就是这样做的。

于 2016-04-20T15:42:47.713 回答
2

在 C# v.7 中,您可以使用内联 out 参数,而无需额外的变量声明:

int.TryParse(TextBoxD1.Text, out int x);
于 2020-03-25T09:52:55.477 回答
1

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

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;
}
于 2017-06-05T12:37:25.773 回答
1

以上所有答案都很好,但对于信息,我们可以使用int.TryParsewhich is safe to convert string to 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在大多数程序上下文中,它总体上更可取。

资料来源:如何在 C# 中将字符串转换为 int?(Int.Parse 和 Int.TryParse 的区别)

于 2020-08-06T07:10:00.740 回答
1

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

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

如果您不知道字符串是整数,请使用TryParse.

C# 7.0您可以使用内联变量声明

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

代码:

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

退税:

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

于 2021-06-25T20:44:52.030 回答
1

这是通过扩展方法执行此操作的版本,如果转换失败,该方法也可以设置默认值。事实上,这就是我用来将字符串输入转换为任何可转换类型的方法:

using System;
using System.ComponentModel;

public static class StringExtensions
{
    public static TOutput AsOrDefault<TOutput>(this string input, TOutput defaultValue = default)
        where TOutput : IConvertible
    {
        TOutput output = defaultValue;

        try
        {
            var converter = TypeDescriptor.GetConverter(typeof(TOutput));
            if (converter != null)
            {
                output = (TOutput)converter.ConvertFromString(input);
            }
        }
        catch { }

        return output;
    }
}

对于我的使用,我将输出限制为可转换类型之一:https ://docs.microsoft.com/en-us/dotnet/api/system.iconvertible?view=net-5.0 。例如,我不需要疯狂的逻辑来将字符串转换为类。

要使用它将字符串转换为 int:

using FluentAssertions;
using Xunit;

[Theory]
[InlineData("0", 0)]
[InlineData("1", 1)]
[InlineData("123", 123)]
[InlineData("-123", -123)]
public void ValidStringWithNoDefaultValue_ReturnsExpectedResult(string input, int expectedResult)
{
    var result = input.AsOrDefault<int>();

    result.Should().Be(expectedResult);
}

[Theory]
[InlineData("0", 999, 0)]
[InlineData("1", 999, 1)]
[InlineData("123", 999, 123)]
[InlineData("-123", -999, -123)]
public void ValidStringWithDefaultValue_ReturnsExpectedResult(string input, int defaultValue, int expectedResult)
{
    var result = input.AsOrDefault(defaultValue);

    result.Should().Be(expectedResult);
}

[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("abc")]
public void InvalidStringWithNoDefaultValue_ReturnsIntegerDefault(string input)
{
    var result = input.AsOrDefault<int>();

    result.Should().Be(default(int));
}

[Theory]
[InlineData("", 0)]
[InlineData(" ", 1)]
[InlineData("abc", 234)]
public void InvalidStringWithDefaultValue_ReturnsDefaultValue(string input, int defaultValue)
{
    var result = input.AsOrDefault(defaultValue);

    result.Should().Be(defaultValue);
}
于 2021-09-02T23:44:13.760 回答
0

您可以尝试以下方法。它将起作用:

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

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

于 2015-07-06T11:17:10.457 回答
0

方法一

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

方法二

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");
}
于 2017-10-18T12:46:28.107 回答
0

此代码在 Visual Studio 2010 中适用于我:

int someValue = Convert.ToInt32(TextBoxD1.Text);
于 2018-01-02T11:10:31.997 回答
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# 如何将字符串转换为 int

于 2021-01-21T12:21:31.740 回答
0
using System;
class HelloWorld {
static void Main()
{
 int experience = 0;
 Console.WriteLine("How many years of experience do you have?");
 var years = Console.ReadLine();
 Int32.TryParse(years, out experience);
 if (experience == 0)
     Console.WriteLine("Inexperienced");
else if (experience == 1)
     Console.WriteLine("Junior");
else if (experience == 2)
     Console.WriteLine("Intermediate");
else if (experience == 3)
     Console.WriteLine("Advanced");
else
     Console.WriteLine("Senior");
   }
}
于 2021-12-06T13:24:44.023 回答
-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.");
        }
    }
}
于 2016-10-27T11:10:11.323 回答