我如何检查错误。如果一个人输入的名称不正确或拼写错误,我希望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();
{
}
}
答案 0 :(得分: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)
这将检查列表中的任何名称是否等于textBox输入的名称:
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.
}
答案 2 :(得分:0)
将所有名称放在集合中,如List或Dictionary,然后使用.Contains()方法。这应该提供更简洁的解决方案。