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は a を返すのでbool、その戻り値を使用して解析試行の結果を決定できます。

int x = 0;

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

興味があれば、 と の違いは次のように要約すると最適ですParseTryParse

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

2 つの違いは、テキスト ボックスの値を変換できない場合、最初の例外は例外をスローするのに対し、2 番目の例外は単に false を返すことです。

于 2009-06-19T20:08:03.320 に答える
16

Convert.ToInt32()char で使用する場合は注意してください。文字のUTF-16コードを返します!

[i]インデックス演算子を使用して特定の位置でのみ文字列にアクセスするcharと、! ではなく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 に答える
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 に答える
12
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

TryParse ステートメントは、解析が成功したかどうかを表すブール値を返します。成功した場合、解析された値が 2 番目のパラメーターに格納されます。

詳細については、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 に答える
6

stringから への変換は、 、、および .NET の整数データ型を反映するその他のデータ型に対してint実行できます。intInt32Int64

以下の例は、この変換を示しています。

これは、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 に答える
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

次を使用して、C# で文字列を int に変換できます。

convert クラスの関数、つまりConvert.ToInt16()Convert.ToInt32()Convert.ToInt64()またはParseおよびTryParse関数を使用します。ここに例を示します

于 2018-05-11T06:16:13.587 に答える
4
int i = Convert.ToInt32(TextBoxD1.Text);
于 2010-05-29T06:39:55.107 に答える
4

これでいい

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

または、使用できます

int xi = Int32.Parse(x);

詳細については、Microsoft Developer Network を参照してください。

于 2017-07-03T06:27:19.130 に答える
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 では、追加の変数宣言なしで inline out パラメーターを使用できました。

int.TryParse(TextBoxD1.Text, out int x);
于 2020-03-25T09:52:55.477 に答える
0

以下を試すことができます。それが動作します:

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

変数 TextBoxD1.Text の文字列値は Int32 に変換され、x に格納されます。

于 2015-07-06T11:17:10.457 に答える
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");
}
于 2017-10-18T12:46:28.107 に答える
-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 に答える