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 PrasadPosted Jan 16, 2022, 5:37 PM
Why are { } compelled in your case? Good question.
Its because of the SCOPE.
Lets see some examples :
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 :
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 MeunierPosted Jan 16, 2022, 8:31 PM
Valerie MeunierPosted Jan 16, 2022, 3:43 PM