1

I have wrote a code with this description: First button calls FuncPopup(); function, after that every popup dialog creates new button. New button Create FuncPopup();. Old buttons should have various behavior.

        private void FuncPopup()
    {
        FuncMenu popup = new FuncMenu();
        popup.ShowDialog();
        if (popup.DialogResult.HasValue && popup.DialogResult.Value)
        {
            i++;
            newBtn[i] = new Button();
            FuncGird.Children.Add(newBtn[i]);
            Grid.SetColumn(newBtn[i], i);
            Grid.SetRow(newBtn[i], j);
            newBtn[i].Click += (sender, e) => clicked(i);
        }
    }
    void clicked(int g) {
        if (g >= i) 
        {
            FuncPopup(); 
        }
        else (g < i){
            OtherFunction();
        }
    }

i is a global variable. I expect Old buttons run OtherFunction(); but they always run FuncPopup();.

1 Answer 1

1

That's because as you said i is global variable, and you attach the following handler:

 newBtn[i].Click += (sender, e) => clicked(i);

And you increment i all the time. You might think that value of i is fixed at the moment you attach this handler but it's not so. i in clicked(i) is the same global variable, which increments with every call. So g always equals i in that handler, and so for all buttons FuncPopup is called.

Instead save i to local variable and use that:

int tmp = i;
newBtn[i].Click += (sender, e) => clicked(tmp);
Sign up to request clarification or add additional context in comments.

1 Comment

Great job, I have defined tmp variable locally, the result became what I expected.

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.