2016-08-26 3 views
-2

私は、ユーザーが彼の名前と年齢を書く必要がある非常に簡単なプログラムを作った。メッセージボックスが表示され、名前と年齢が表示されます。 (http://imgur.com/a/Kqb1rC#で入力が文字列かバイトかをチェックする方法は?

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

    private void txtName_TextChanged(object sender, EventArgs e) 
    { 
     txtAge.Enabled = true; 
    } 

    private void txtAge_TextChanged(object sender, EventArgs e) 
    { 
     cmdSubmit.Enabled = true; 
    } 

    private void cmdSubmit_Click(object sender, EventArgs e) 
    { 
     var name = txtName.Text; 
     var age = Convert.ToByte(txtAge.Text); 
     MessageBox.Show($"Your name is {name} and You're {age} years old."); 
    } 

    private void cmdExit_Click(object sender, EventArgs e) 
    { 
     Close(); 
    } 
} 

私はこれをどのように操作を行うことができます。年齢は文字列の場合、メッセージボックスがポップアップし、「年齢が数とユーザーが再試行する必要はない」と言いますか?

+1

が上に読む0(ゼロ)にTryParseは(パラメータアウト)年齢を設定します番号でない場合は[ 'int.Parse()'](https://msdn.microsoft.com/en-us/library/system.int32.parse(v = vs.110).aspx) –

+0

無効な入力を拒否できるMaskedTextBoxがあります。 https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx – LoekD

答えて

1

技術的に変換には何も問題はありません。これは、すべてのデータが有効であれば動作します。

private void cmdSubmit_Click(object sender, EventArgs e) 
    { 
     var name = txtName.Text; 
     var age = Convert.ToByte(txtAge.Text); 
     MessageBox.Show($"Your name is {name} and You're {age} years old."); 
    } 

データを検証するにはいくつかの方法がありますが、ここでは別の方法があります。

private void cmdSubmit_Click(object sender, EventArgs e) 
    { 
     string name = txtName.Text; 
     short age; //This is an Int16 with a range of -32,768 to +32,767 
     short.TryParse(txtAge.Text,out age); 
     string ageStatement = age == 0 ? "your age is unknown" : 
             $"you're {age} years old"; 
     MessageBox.Show($"Your name is {name} and {ageStatement}."); 

TryParse

short.TryParse(txtAge.Text,out age); 

txtAge.Text内の文字列データが

1

これを試してみてください:

private void cmdSubmit_Click(object sender, EventArgs e) 
{ 
    var name = txtName.Text; 
    int age; 
    if(Int32.TryParse("txtAge.Text, out age)) 
    { 
     MessageBox.Show($"Your name is {name} and You're {age} years old."); 
    } 
    else 
    { 
     MessageBox.Show("Enter valid age");   
    } 

} 
2
var name = txtName.Text; 
Byte outAge; 
bool result= Byte.TryParse(txtAge.Text, NumberStyles.Integer,null as IFormatProvider, out outAge); 

if (!result) 
{ 
//show your message box; 
} 
else 
{ 
var age=outAge; 
} 

簡単な説明のために下のリンクをご確認ください

https://msdn.microsoft.com/en-us/library/tkktxbeh(v=vs.110).aspx

1

は「NumericUpDown最低で制御し、いくつかの合理的な値に設定された最大値を使用し、ドンしてみてください検証と解析を再実装しないでください