1

I would like to use label arrays but it is not working i don't know what i am missing. Here is the code I am trying to get to work:

for (int x = 1; x <= 10; x++)
{
    Label[] label1 = new Label[10];  
    label1[x] = new Label();
    label1[x].AutoSize = true;
    label1[x].Text = "text";
    label1[x].Left +=10;
    label1[x].Top +=10;
}
3
  • 2
    In addition to Gilad Green's point, if you actually want these labels to appear in the UI somewhere, they have to be added to some control's Controls collection. Commented Oct 6, 2016 at 15:20
  • 1
    Also, you have an off by 1 error here in your loop. You have nothing in label[0] then label[10] doesn't exist. It appears Gilad's answer has addressed this. Commented Oct 6, 2016 at 15:23
  • @Tészta Sajtos - This time it was possible to understand the problem from the code but for next time please when you say "not working" specify what is going wrong: exception, unexpected behavior/output.... Commented Oct 6, 2016 at 16:03

2 Answers 2

10

You are initializing a new Label1 array in each iteration so you will eventually have only the last one with 1 item at the last place.

Move the declaration of the label1 outside of the loop:

//Move this line outside of the loop's scope
Label[] label1 = new Label[10];

//Loop from 0 to the Length of the array instead of repeating 10 again
for (int x = 0; x < label1.Lenth; x++)
{   
    label1[x] = new Label();
    label1[x].AutoSize = true;
    label1[x].Text = "text";
    label1[x].Left +=10;
    label1[x].Top +=10;
}

I'd recommend that you look in MSDN about using arrays:

Sign up to request clarification or add additional context in comments.

Comments

4

In order to avoid such errors (wrong filling out), try generating arrays:

int n = 10;

Label[] label1 = Enumerable
  .Range(0, n)
  .Select(x => new Label() {
     AutoSize = true,
     Text = "text",
     Left = x * 10,
     Top = x * 10, 
   })
  .ToArray(); 

3 Comments

I do like linq and it is a great tool but I think that for this case for this level this solution is an overkill.. It is quite basic array handling knowledge
Seems like a fine enough answer, but it certainly is a bit much for a presumed beginner.
This kind of solution (generating) allows to forget about array creation, index range; e.g. code in the question uses 10 as a magic number in (for.. x <= 10...) and in array creation new Label[10]; wrong indexing (1-based instead of zero based) etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.