1

I'm new with windows forms and I've come up with an UI: Small cut of the UI

First thing you'll notice are the 16 labels and textboxes I have created. Windows Forms / Visual studio automatically generates these in the following manner:

    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label3;
    ...
    private System.Windows.Forms.Label label16;

That's fine but I've hit a wall after I try to read information from those fields due to the fact I have to address every individual label with eg.

    label1.Text;
    label2.Text;
    ...
    label16.Text;

I thought of using a for loop until I stumbled upon the fact that the names aren't the same / incrementable. At first I settled with just doing it like:

    Label[] _labels = new Label[16];
    this._labels[0] = label1;
    this._labels[1] = label2;
    this._labels[2] = label3;
    ...
    this._labels[15] = label16; // I have to instantiate the labels in order to work with them.

But as my code progressed, I also had to do the same for the textboxes whenever I needed to retrieve data from those and it quickly became non-DRY code.

I tried doing something along the lines of:

    for(int i = 0; i < _labels.Length; i++) {
       _labels[i] = label{i}; // this won't work sadly enough
    }

But that didn't work out neither. Unless I really have to, is there an efficient way of either calling and storing those labels / textboxes?

Thanks!

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
CCG
  • 97
  • 1
  • 10
  • Your question kinda sounds like _code improvement_ and if so may be off-topic for SO. It _may_ be better suited for another SE site but be sure to read the relevant FAQ; and/or re-wording your question as necessary before cross-posting. [ask]. Good luck! –  Dec 07 '19 at 01:41
  • @MickyD That is silly of me! I'll delete it if it gets on hold! Thank you for pointing that out – CCG Dec 07 '19 at 01:45

1 Answers1

0

You can loop on the form's elements with For or Foreach and Linq :

using System.Linq;
var labels = Controls.OfType<Label>()
.Where(label => label.Name.StartsWith("labels"));  // get all you labels for foreach (i assume your lable name start with "label"
 Label[] _labels = new Label[16]; // new labels
  int i = 0;
  foreach (var label in labels)
   {
      _labels[i] = label;
       i++;
   }

And you can do same for Textbox and etc. If label names are not start with "label" you can just dissmis .Where part :

    var labels = Controls.OfType<Label>().ToList();
Mohammad
  • 1,549
  • 1
  • 15
  • 27