2010-09-07 52 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