-1

I have multiple text blocks I want to compare the text values of with whatever the current random value is in my array, so I can "gray out" the text block when it gets "opened".

This code works for 1 text block, but I was wondering how I could do it for all 26 of my blocks w/o having to type out each one? Is there a way I can reference all my blocks, kind of like using the same click event for all my buttons?

if (money[turns]==Convert.ToInt32(tb0.Text))
                    {
                        tb0.Foreground = Brushes.Gray;
                    }
Audie
  • 11
  • 3
  • Why don't you loop through all your `TextBox`es doing this validation? You have them in the `Controls` property of the form, just check its type to make sure it's the one you are interested in. – Andrew Jan 04 '16 at 17:32
  • 1
    What is the application type? Forms? WPF? – Alexei - check Codidact Jan 04 '16 at 17:32
  • You're asking the wrong question. When you need to do this, it's almost always a design smell. You should use data binding, or the tag or name to identify which control displays what. Anyway "[your UI framework] find all controls" will yield plenty of results. – CodeCaster Jan 04 '16 at 17:35
  • Sorry! WPF is the application type. The list solution worked perfectly for me and what I was looking for. – Audie Jan 05 '16 at 18:09

2 Answers2

0

If Windows.Forms you can iterate through all your controls of type TextBox and compare your text to the one in each TextBox. The code should like this:

bool exists = GetAll(this, typeof(TextBox)).Any(t => t.Text.Equals(yourText));

As already suggested, it would be better to use databinding and do the search in your objects, rather than into your interface.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
0

As addition to Alexei, if you want only compare specific TextBlock, first you can insert your TextBlock into a List

List<TextBlock> listTextBlock = new List<TextBlock>();
list.Add(tb0);
list.Add(tb1);

... so you just using loop to check each TextBlock.

foreach(TextBlock item in listTextBlock)
{
   if (money[turns]==Convert.ToInt32(item.Text))
   {
      item.Foreground = Brushes.Gray;
   }
}
I Putu Yoga Permana
  • 3,980
  • 29
  • 33