C # What is an efficient way to do this php "eval" style code

I have a windows application in C #, in the form I have 12 shortcuts with names

label1, label2 , ...............

I have an array of 12 numbers (after some calculation)

like:

int[] nums = new int[12] {1, 0, 4, 6,.............};

I want to assign a value from an array in a loop to each label element. Accordingly

sort of

 for (int i = 1; i <= 12; i++) {
     label+i.Text = nums[i-1].ToString();
   }

What is an effective way to do this?

thank

+3
source share
3 answers

Create the appropriate array of labels:

Label[] labels = new Label[12] { label1, label2, ... };

for(int i = 0; i < 12; i++)
{
    labels[i].Text = nums[i].ToString();
}
+7
source

If all labels belong to the same control (for example, Panel), you can use the find control to accomplish this assignment:

for(int i = 0;i < 12; i++)
{
    Label lbl = myPanel.FindControl("Label" + i.ToString());
    lbl.Text = nums[i].ToString();
}
+5
source

FindControl :

for (int i = 0; i < nums.Length; i++) {
  (Form.FindControl("label" + i.ToString()) as Label).Text = nums[i].ToString();
}
+1

Source: https://habr.com/ru/post/1779250/


All Articles