The @Leonardol explanation is very good for your problem! But I will leave an additional code to solve another type of problem if it occurs in your scenario.
Leonardo’s scenario will work very well if all his Abels are inside the form as primary control, if they are daughters of some other control, such as, for example, a Panel (they are inside a panel), you will not be able to find them in your foreach
.
To solve this scenario, we need to create a recursive method that will navigate all the controls of our screen, until the last level, search for all the Abels contained in this form and define a new value for the property Text
:
public void DefinirValorLabels(Control control, Random random)
{
// Se nosso controle for uma label, definimos a propriedade "Text" como um número aleatório
if (control is Label)
control.Text = random.Next(1, 100).ToString();
// Se o controle não é uma label, ele pode ser um panel (por exemplo), ou seja, dentro desse controle (panel) pode haver outras labels.
// Por esse motivo, iremos percorrer nosso controle e ver se possuimos mais labels para definirmos um valor.
foreach (Control ctrl in control.Controls)
{
DefinirValorLabels(ctrl, random);
}
}
To use, simply call the method as follows:
Random random = new Random();
DefinirValorLabels(this, random);
I think in the future I’ll need this, thank you!
– D. Rodrigues