Search code examples
c#error-checking

Error checking for if a person enters an incorrect name


How would I check for errors. If a person enters an incorrect name or doesnt spell it correctly I would like for a messagebox.show to display a message stating "Incorrect name or spelling"

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();

        {

        } 

    }

Solution

  • You will need to keep a list or 'dictionary' of correct names.

    Then, you can match the text against the entries in the dictionary.

    Code would look similar to the following:

    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");
        }
    }
    

    You probably want to use correct spelling in your implementation.

    Have a look at the documentation for HashSet to get a better idea of how to use it.