があり、それを に変換してデータベースに保存しTextBoxD1.Text
たいと考えています。int
これどうやってするの?
これを試して:
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
}
興味があれば、 と の違いは次のように要約すると最適ですParse
。TryParse
TryParse メソッドは Parse メソッドと似ていますが、TryParse メソッドは変換が失敗した場合に例外をスローしません。s が無効で正常に解析できない場合に、例外処理を使用して 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);
2 つの違いは、テキスト ボックスの値を変換できない場合、最初の例外は例外をスローするのに対し、2 番目の例外は単に false を返すことです。
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
文字列を解析する必要があり、それが本当に整数の形式であることも確認する必要があります。
最も簡単な方法は次のとおりです。
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 ステートメントは、解析が成功したかどうかを表すブール値を返します。成功した場合、解析された値が 2 番目のパラメーターに格納されます。
詳細については、Int32.TryParse メソッド (文字列、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、特にMSDNのNumberFormatInfoを参照してください。
独自の拡張メソッドを記述できます
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();
string
から への変換は、 、、および .NET の整数データ型を反映するその他のデータ型に対してint
実行できます。int
Int32
Int64
以下の例は、この変換を示しています。
これは、int 値に初期化されたデータ アダプター要素を (情報として) 示しています。同じことを次のように直接行うことができます。
int xxiiqVal = Int32.Parse(strNabcd);
元。
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
次のいずれかを使用できます。
int i = Convert.ToInt32(TextBoxD1.Text);
また
int i = int.Parse(TextBoxD1.Text);
//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;
}
拡張メソッドを使用することもできるため、より読みやすくなります (ただし、通常の 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);
}
}
そして、そのように呼び出すことができます:
文字列が「50」などの整数であることが確実な場合。
int num = TextBoxD1.Text.ParseToInt32();
確信が持てず、クラッシュを防ぎたい場合。
int num;
if (TextBoxD1.Text.TryParseToInt32(out num))
{
//The parse was successful, the num has the parsed value.
}
より動的にして、double、float などにも解析できるようにするには、汎用拡張を作成します。
次を使用して、C# で文字列を int に変換できます。
convert クラスの関数、つまりConvert.ToInt16()
、Convert.ToInt32()
、Convert.ToInt64()
またはParse
およびTryParse
関数を使用します。ここに例を示します。
int i = Convert.ToInt32(TextBoxD1.Text);
これでいい
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
または、使用できます
int xi = Int32.Parse(x);
parse メソッドを使用して、文字列を整数値に変換できます。
例えば:
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
私がいつもこれを行う方法は次のとおりです。
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.
}
}
}
これは私がそれを行う方法です。
C# v.7 では、追加の変数宣言なしで inline out パラメーターを使用できました。
int.TryParse(TextBoxD1.Text, out int x);
以下を試すことができます。それが動作します:
int x = Convert.ToInt32(TextBoxD1.Text);
変数 TextBoxD1.Text の文字列値は Int32 に変換され、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");
}
これはあなたを助けるかもしれません;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.");
}
}
}