There are 2 buttons, with 1 button we create 2 buttons like this:

private static int X = 100; private static int Y = 100; System.Windows.Forms.Button buttonDyn private void buttonDynamic_Click(object sender, EventArgs e) { AddButton(X, Y); X += 100; } private void AddButton(int x, int y) { // создаСм ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ» buttonDyn = new System.Windows.Forms.Button(); // устанавливаСм Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΡ‹Π΅ свойства buttonDyn.Location = new System.Drawing.Point(x, y); buttonDyn.Name = "button1"; buttonDyn.Size = new System.Drawing.Size(75, 23); buttonDyn.TabIndex = 0; buttonDyn.UseVisualStyleBackColor = true; // button1_Click - функция ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ события наТатия Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡƒ buttonDyn.Click += new System.EventHandler(buttonDyn_Click); Controls.Add(buttonDyn); // добавляСм Π½Π° Ρ„ΠΎΡ€ΠΌΡƒ //Π²ΠΎΡ‚ здСсь мСняСм Ρ†Π²Π΅Ρ‚ ΠΊΠ½ΠΎΠΏΠΊΠΈ buttonDyn.BackColor = Color.Chartreuse; } 

When you click on the 2 button (which we created dynamically), button 1 and button 2 should change color:

 private void buttonDyn_Click(object sender, EventArgs e) { buttonDynamic.BackColor = Color.DarkBlue; buttonDyn.BackColor = Color.DarkBlue; } 

But the color changes only on the first button. I suppose that the program does not understand to which button this applies. buttonDynamic is created dynamically and there can be a lot of them. Then how to solve this problem?

  • to store links to buttons in the List<Button> , in the handler to iterate over the List and assign a color - Exodium
  • @Exodium is a good idea, but it still doesn’t work. Although if we change the text on the button everything works. I think it's in 'Controls.Add (buttonDyn)', but even if we put it before the list item, nothing happens. - polsok

1 answer 1

Everything is simple, the sender parameter is provided in the event handlers. sender always (not counting exotic implementations and errors) contains a reference to the object that initiated this event.

 private void buttonDyn_Click(object sender, EventArgs e) { //ΠΏΠΎ ΠΊΠΎΠ΄Ρƒ Π²Ρ‹ΡˆΠ΅ это постоянная ΠΊΠ½ΠΎΠΏΠΊΠ° buttonDynamic.BackColor = Color.DarkBlue; //для динамичСских мСняСм //buttonDyn.BackColor = Color.DarkBlue; //Π½Π° (sender as Button).BackColor = Color.DarkBlue; } 

and return buttonDyn back to the state of a local variable, no good from this field, just confusion.