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?
List<Button>, in the handler to iterate over theListand assign a color - Exodium