Home > Blockchain >  How to handle a c# WinForms event correctly
How to handle a c# WinForms event correctly

Time:04-14

        for (var i = 0; i < 3; i  )
        {
            for (var j = 0; j < 3; j  )
            {
                numbers[i, j] = new Button();
                numbers[i, j].Location = new Point(row, input.Height   column);
                row  = 40;
                numbers[i, j].Size = new Size(30, 30);
                numbers[i, j].Text = k.ToString();
                k  ;
                numbers[i, j].Click  = (e, sender) =>
                {
                    input.Text  = k.ToString();
                };
                Controls.Add(numbers[i, j]);
            }
            row = 0;
            column  = 40;
        }

I have such a problem when starting the program and pressing any button outputs to the input field 9 I guess that there is a problem in the event, but I can't figure out how to fix it so that, say, when pressing the 2 button, the input field outputs 2 and not 9

CodePudding user response:

The problem ist that at the time the event handler is executed, the value of the variable k is already 9.

You could either move the calculation of k.ToString() to a local variable outside the event handler (note that I swapped the event handler parameters sender and e as convention):

var text = k.ToString();
numbers[i, j].Click  = (sender, e) =>
{
  input.Text  = text;
};

As you already have the text "0" to "9" as button text, this can also be simply:

numbers[i, j].Click  = (sender, e) =>
{
  input.Text  = ((Button)sender).Text;
};

CodePudding user response:

I'd use Tag property of a Control:

numbers[i, j].Text = k.ToString();
numbers[i, j].Tag = k; // store the value you need within the button itself
k  ;
numbers[i, j].Click  = (sender, e) =>
{
    input.Text  = sender.Tag.ToString();
};
  • Related