Home > front end >  How to apply constraint on a textbox. Only specific information/words that's written in the tex
How to apply constraint on a textbox. Only specific information/words that's written in the tex

Time:04-24

I want the user to be able to write something inside of a textbox, and add that written value to a listbox.

But here is the problem :

The user is allowed to write anything he wants inside of the textbox. But when the user wants to add the value he just wrote to the listbox, only these words can be added to the listbox:

  • Tiger
  • Lion
  • Sheep
  • Rat
  • Mouse
  • Flamingo
  • Wolf

The value that's written inside of the textbox can be added to the listbox by pressing a button.

Thanks in advance!

CodePudding user response:

You can store the words in some collection, say in HashSet<string> and then on button click check if the word input by user is in the collection.

In case of WinForms you can put it like this:

// Words we allow to add
private static HashSet<string> s_Words = 
   new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
     "Tiger", "Lion", "Sheep", "Rat", "Mouse", "Flamingo", "Wolf",
};

// On button click we can add the word from myTextBox into myListBox
private void myButton_Click(object sender, EventArgs e) {
  // Let us be nice and tolerate leading and trailing whitespaces 
  string text = myTextBox.Text.Trim();

  // If word is in the collection ... 
  if (s_Words.ContainsKey(text))
    myListBox.Items.Add(text);  // ... we add it into to the listbox
}
  •  Tags:  
  • c#
  • Related