Access variable-based elements

7

I need to assign the value to a label , example: xrLabel1.text = "teste" , but I have multiple labels where only the number in the final example changes:

xrLabel1.text = "teste";
xrLabel2.text = "teste";
xrLabel3.text = "teste";

How do I populate these values using a loop as in the example below:

for (int i = 0; i < 3; i++)
    string.Concat("xrLabel", i.ToString()).Text = "teste";
    
asked by anonymous 20.05.2015 / 01:07

2 answers

3

You can search the object by name:

for (int i = 0; i < 3; i++) {
    XRLabel label = (XRLabel)this.Controls[string.Concat("xrLabel", i.ToString())];
    label.text = "teste"; 
}
    
20.05.2015 / 01:58
2

One way to do this would be to use a LINQ expression to select all tags of the form, and Enumerable.Zip iterate over the < in> labels and the result of select of DataTable :

// Simulando os dados do teu DataTable
DataTable tabela = new DataTable("Jogadores");
tabela.Columns.Add(new DataColumn("Nome",  typeof(string)));
tabela.Columns.Add(new DataColumn("Idade", typeof(int)));
tabela.Columns.Add(new DataColumn("Sexo",  typeof(char)));

tabela.Rows.Add("Maria",   20, 'f');
tabela.Rows.Add("Leticia", 25, 'f');
tabela.Rows.Add("Pedro",   30, 'm');
tabela.Rows.Add("Tiago",   40, 'm');
tabela.Rows.Add("Joao",    29, 'm');

// Selecionar linhas onde o campo idade seja maior ou igual a 29
DataRow[] resultados = tabela.Select("Idade >= 29");

// No caso do AP ele usou this.Controls["PageHeader"].AllControls<XRLabel>()
var labels = this.Controls.OfType<XRLabel>(); 

foreach (var tupla in labels.Zip(resultados, Tuple.Create)){
    XRLabel label = tupla.Item1 as XRLabel;
    string valor = tupla.Item2.Field<String>(0); // Valor do campo "Nome"
    label.Text = valor;
}
    
20.05.2015 / 01:42