3 Replies - 205 Views - Last Post: 07 February 2012 - 12:03 PM Rate Topic: -----

Topic Sponsor:

#1 scolty  Icon User is offline

  • D.I.C Regular

Reputation: 2
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Unique values in textboxes

Posted 07 February 2012 - 10:39 AM

Evening guys,

Im trying to figure out how to run through the collection of TextBoxes and check that the text is unique.

Any ideas?

This post has been edited by scolty: 07 February 2012 - 10:42 AM

Is This A Good Question/Topic? 0
  • +

Replies To: Unique values in textboxes

#2 Robin19  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 169
  • View blog
  • Posts: 358
  • Joined: 07-July 10

Re: Unique values in textboxes

Posted 07 February 2012 - 10:49 AM

stub of brute force method
allTexts = new List<string>
foreach(Control c in Control)
   if (c is Textbox)
      text = c.Text
      if (allTexts.Contains(text))
         not unique!
      allTexts.Add(text)

Was This Post Helpful? 2
  • +
  • -

#3 scolty  Icon User is offline

  • D.I.C Regular

Reputation: 2
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Re: Unique values in textboxes

Posted 07 February 2012 - 11:02 AM

Thats pretty sweet, thanks very much!
Was This Post Helpful? 0
  • +
  • -

#4 Curtis Rutland  Icon User is offline

  • (╯°□°)╯︵ (~ .o.)~
  • member icon

Reputation: 3134
  • View blog
  • Posts: 5,402
  • Joined: 08-June 10

Re: Unique values in textboxes

Posted 07 February 2012 - 12:03 PM

Just because I like LINQ so much, here's a LINQ-ish way to do this:

var textBoxes = Controls.OfType<TextBox>().GroupBy(t => t.Text.ToLower()).ToList();
var unique = textBoxes.Where(g => g.Count() == 1).SelectMany(g => g);
var duplicates = textBoxes.Where(g => g.Count() > 1).SelectMany(g => g);
unique.ToList().ForEach(t=>t.BackColor = Color.Green);
duplicates.ToList().ForEach(t => t.BackColor = Color.Red);



The first line fetches all controls on the form that are TextBoxes (you could use a specific panel or collection, if you want). Then it groups them by their lower-case text ("ABCD" matches "abcd"). Grouping is convenient because it allows you to separate collections by conditions. GroupBy results in a collection of collections (think IEnumerable<IEnumerable<TextBox>>).

Then, we take that collection of groups and filter it. First for all those with a count of one. Then SelectMany allows us to flatten our collection of collections into a single collection of textboxes. Now we have all the textboxes with unique values. We can do the same for duplicates.

The next two lines are just to show that it worked on the form. The dups turn red, and the uniques turn green.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1