2010-09-07 78 views
0

如何檢查錯誤。如果一個人進入了不正確的名稱或犯規拼寫正確我想了messagebox.show顯示一條消息,說明「不正確的名稱或拼音」檢查是否有人輸入錯誤名稱時出錯

private void button1_Click(object sender, EventArgs e) 
    { 
     String Andrea; 
     String Brittany; 
     String Eric; 
     if (textBox1.Text == ("Andrea")) 
      Commission.Text = (Convert.ToDouble(textBox2.Text)/10).ToString(); 
     if (textBox1.Text == ("Brittany")) 
      Commission.Text = (Convert.ToDouble(textBox2.Text)/10).ToString(); 
     if (textBox1.Text ==("Eric")) 
      Commission.Text = (Convert.ToDouble(textBox2.Text)/10).ToString(); 

     { 

     } 

    } 

回答

2

您將需要保持一個列表或「字典」正確的名字。

然後,您可以將文本與詞典中的條目進行匹配。

代碼將類似於以下內容:

HashSet<string> correctNames = ;// initialize the set with the names you want 

private void button1_Click(object sender, EventArgs e) 
{ 
    if (correctNames.Contains(textBox1.Text)) 
     Commission.Text = (Convert.ToDouble(textBox2.Text)/10).ToString(); 
    else 
    { 
     MessageBox.Show("The speling of the naem " + textBox1.Text + " was incorect", "Bad Spelling Error"); 
    } 
} 

你可能想在你的方案中使用正確的拼寫。

看看the documentation for HashSet可以更好地瞭解如何使用它。

+1

+1這將是有趣的,如果消息是「壞Speling Eror」 – SwDevMan81 2010-09-07 17:22:28

+0

@SwDev,固定':P' – jjnguy 2010-09-07 17:25:10

+0

哈哈真好!良好的HashSet建議,查找可能比list.Contains() – SwDevMan81 2010-09-07 17:28:19

0

將集合中的所有名稱(如List或Dictionary)拋出,然後使用.Contains()方法。這應該提供一個更好的解決方案。

1

這將檢查列表中的任何名稱等於文本框中輸入名稱:

List<string> nameList = new List<string>(); 

nameList.Add("Andrea"); 
nameList.Add("Brittany"); 
nameList.Add("Eric"); 

if (nameList.Contains(textBox1.Text)) 
{ 
    //Process name here. 
} 
else 
{ 
    //Show messagebox here. 
} 
+0

...或使用「Contains」。 – Timwi 2010-09-07 17:09:50

+0

是的,在發佈後才意識到,哈。 – Ocelot20 2010-09-07 17:14:31