Hi
I have 6 labels on the form (from toolbox). Now i'm trying to catch them., but this code gives "embedded statement cannot be a declaration ..."
Thanks.
private void button1_Click(object sender, EventArgs e)
{
for (int k = 1; k <= 6; k++)
Label lbl = (Label)Controls["label" + k.ToString()]; // error
}

Ranganath PrasadRank #2,004 · 725 reputationPosted Jan 16, 2022, 12:37 PM EST
Why are { } compelled in your case? Good question.
Its because of the SCOPE.
Lets see some examples :
for(int i=0; i<10;i++) Console.Writeline(i); // Perfectly fine int x = 0; for(int i=0; i<10; i++) x = i; // this is also fine because 'x' is declared outside for loop for(int i=0; i<10; i++) int x = i; // NO, not allowed. Why?As you know, in the above scenario, we are declaring a new variable 'x' inside for loop and assigning a value to it. And once the for loop execution is finished, 'x' is destroyed. So what did we accomplish with 'int x = i' in the for loop? Nothing. So, the compiler figured out that 'declaring and assigning a variable in a for single-statement for loop without braces does NOT do anything' and so it threw an error.
We can fool the compiler by including that statement in curly braces, like shown below :
for(int i=0; i<10; i++){ int x = i; }In this case, compiler thinks " Okay, since it is a block now, the dev might include some more statements in that block where he will use that 'x' - so lets not throw any error"
So, now its time to review your code ( below ) and see if you are acheiving anything with that 'lbl' or simply fooling the compiler :) :) .
for (int k = 1; k <= 3; k++)
{
Label lbl = (Label)Controls["label" + k.ToString()];
}
Valerie MeunierRank #1,527 · 1K reputationPosted Jan 16, 2022, 10:43 AM EST
Valerie MeunierRank #1,527 · 1K reputationPosted Jan 16, 2022, 3:31 PM EST