Search code examples
c#listforeachtextboxcontains

checking if textbox contains a word not working


It only seems to detect/check the first word in the list.

private bool ContentCheck()
    {
        List<string> FilteredWords = new List<string>()
        {
            "duck",
            "donkey",
            "horse",
            "goat",
            "dog",
            "cat",                  //list of censored words
            "lion",
            "tiger",
            "bear",
            "crocodile",
            "eel",
        };
        foreach (var e in FilteredWords)
        {
            if (memoEdit1.Text.Contains(e))
            {
                return true; 
            }
            else
            {
                return false;
            }
        }
        return false;
    }

 private void button_click (object sender, EventArgs e)

  {

   if (ContentCheck() == false)
   {
                    //do something
   }

   else if (ContentCheck() == true)
   {
     MessageBox.Show("Error: Offensive word.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
 }

Solution

  • Both situations in the if statement inside of your foreach block results in a return. Think about that for a second, the program will iterate the first item in the list, if it's a swearword it will return, if not it will also return. Both of those will exit the code and so the next item will never be iterated.

    To fix this you need to change

    foreach (var e in FilteredWords)
    {
        if (memoEdit1.Text.Contains(e))
        {
            return true; 
        }
        else
        {
            return false;
        }
    }
    return false;
    

    to

    foreach (var e in FilteredWords)
    {
        if (memoEdit1.Text.Contains(e))
        {
            return true; 
        }
    }
    return false;