Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply constraint on a textbox. Only specific information/words that's written in the textbox can be added to listbox in C#

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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!

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading