Home > Back-end >  Put textboxes in an array
Put textboxes in an array

Time:10-11

I have a about 80 textboxes and I have named them as

s1v1, s1v2, ..... s12v7. 

But I want to put them in an array or make a list of them so I can use them easily in for loops I use the arrray below but I believe that there is an easier way to do it . Can you tell me what is the best way to solve it ?

TextBox[,] girdiler = new TextBox[,]{ 
  { s1v1, s1v2, s1v3, s1v4, s1v5, s1v6, s1v7 }, 
  { s2v1, s2v2, s2v3, s2v4, s2v5, s2v6, s2v7 }, 
  { s3v1, s3v2, s3v3, s3v4, s3v5, s3v6, s3v7 },
  { s4v1, s4v2, s4v3, s4v4, s4v5, s4v6, s4v7 }, 
  { s5v1, s5v2, s5v3, s5v4, s5v5, s5v6, s5v7 }, 
  { s6v1, s6v2, s6v3, s6v4, s6v5, s6v6, s6v7 },
  { s7v1, s7v2, s7v3, s7v4, s7v5, s7v6, s7v7 }, 
  { s8v1, s8v2, s8v3, s8v4, s8v5, s8v6, s8v7 }, 
  { s9v1, s9v2, s9v3, s9v4, s9v5, s9v6, s9v7 },
  { s10v1, s10v2, s10v3, s10v4, s10v5, s10v6, s10v7 }, 
  { s11v1, s11v2, s11v3, s11v4, s11v5, s11v6, s11v7 }, 
  { s12v1, s12v2, s12v3, s12v4, s12v5, s12v6, s12v7 } 
};

As you can see it is too long and I want to make it easier.

CodePudding user response:

You can query Controls with a help of Linq in order to organize all TextBoxes into a collection:

using System.Linq;

... 

var boxes = Controls
  .OfType<TextBox>()
  .Where(box => !string.IsNullOrEmpty(box.Name)) // to be on the safe side
  .ToDictionary(box => box.Name, box => box);

TextBox[,] girdiler = new TextBox[12, 7];

for (int s = 1; s <= girdiler.GetLength(0);   s)
  for (int v = 1; v <= girdiler.GetLength(0);   v) 
    girdiler[s - 1, v - 1] = boxes[$"s{s}v{v}"];   
  • Related