Reputation: 135
I'm currently trying to add a specific action to an array of labels but the variables are kept only between the {}
.
_arr[i].Click += (a, b) => {
z++;
numarfinal = Convert.ToString(z);
MessageBox.Show(Convert.ToString(numarfinal));
};
Outside {}
neither variable z
nor numarfinal
has changed but the MessageBox.Show
reports that their parameters have changed.
Here is the whole function:
Label[] _arr = new Label[20];
Label[] _dinamic = new Label[20];
private static Random _r = new Random();
string numarfinal ;
private void button1_Click(object sender, EventArgs e)
{
int z=0;
int limita = Convert.ToInt16(textBox1.Text);
limita = int.Parse(textBox1.Text);
if (limita > 20)
textBox1.Text = "Do sth";
int randomnumber = _r.Next(20);
for(int i=0;i<limita;i++)
{
do
{
randomnumber = _r.Next(20);
} while (randomnumber==0);
_arr[i] = new Label();
_arr[i].Click += (a, b) =>
{
z++;
numarfinal= Convert.ToString(z);
MessageBox.Show(Convert.ToString(numarfinal));
};
_arr[i ].Text = Convert.ToString(randomnumber);
_arr[i ].Size = new Size(50,50);
_arr[i ].Location = new Point(55*i,60);
testlabel.Text = Convert.ToString(numarfinal); // the label value remain nothing (numarfinal's initial value)
this.Controls.Add(_arr[i]);
}
Upvotes: 0
Views: 262
Reputation: 244837
The problem is that you set testlabel.Text
once, while the value of numarfinal
is still null. When one of the labels is clicked and its event handler is executed, the value of numarfinal
is changed, but the value of testlabel.Text
isn't.
One way to fix that is to simply set testlabel.Text
in the event handler lambda:
_arr[i].Click += (a, b) =>
{
z++;
numarfinal = Convert.ToString(z);
testlabel.Text = numarfinal;
MessageBox.Show(Convert.ToString(numarfinal));
};
Upvotes: 1
Reputation: 2535
Clicking button1 will never cause the line numarfinal = Convert.ToString(z);
to be reached because your are only attaching the delegate there. When you assign the delegate with (a, b) => {...}
, the code within the {}
is not called until the respective event is actually raised (i.e., clicking the respective label).
Upvotes: 0
Reputation: 451
The z value is being changed in the click events of the labels. If you want to see the change in your testlabel you should change its text "in the click events". If you want to change numarfinal every time you add a label you should put your code out of click events and if you want numarfinal change every time you click on a label your code should be were it already is.
Upvotes: 0