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

我该怎么做?

有帮助吗?

解决方案

试试这个:

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
}

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

  

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

其他提示

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(..);
}
int.TryParse()

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

int myInt = int.Parse(TextBoxD1.Text)

另一种方式是:

bool isConvertible = false;
int myInt = 0;

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

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

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

最简单的方法是:

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
}
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

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

参见 Int32.TryParse Method(String,Int32) 了解更多详细信息。

享受它......

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

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

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

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

欲了解更多信息,请阅读CultureInfo,特别是 NumberFormatInfo

在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

您可以编写自己的扩展方法 在代码中的任何地方只需调用

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

TryParse文档中所述,TryParse()返回boolean表示找到了有效的数字:

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
}

您可以使用

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

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

string int 的转换可以完成: int Int32 Int64 和其他反映.NET中整数数据类型的数据类型

以下示例显示了此转化:

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

int xxiiqVal = Int32.Parse(strNabcd);

实施例

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

链接以查看此演示

int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;
//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;
}

这样做

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

或者您可以使用

int xi=Int32.Parse(x);

参考 Microsoft Developer Network获取更多信息

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

转换类的功能,即 Convert.ToInt16() Convert.ToInt32() Convert.ToInt64()或使用< code> Parse 和 TryParse 函数。举例此处

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

如果没有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 ;
}
int i = Convert.ToInt32(TextBoxD1.Text);

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

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

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

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

例如:

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

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

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

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

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

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

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

此代码适用于Visual Studio 2010:

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

这可能对你有帮助; 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.");
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top