The task when you click on the button to create another button with a specific color of the button. Add a button to the form when clicked, we create a button with the specified color.

private static int X = 100; private static int Y = 100; private void buttonDynamic_Click(object sender, EventArgs e) { AddButton(X, Y); X += 100; } private void AddButton(int x, int y) { // создаСм ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ» System.Windows.Forms.Button 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.BackColor = Color.Chartreuse; buttonDyn.UseVisualStyleBackColor = true; // button1_Click - функция ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ события наТатия Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡƒ buttonDyn.Click += new System.EventHandler(button1_Click); Controls.Add(buttonDyn); // добавляСм Π½Π° Ρ„ΠΎΡ€ΠΌΡƒ } 

When you click on the buttonDynamic button, a new button appears, but its color is standard gray. What am I doing wrong?

    1 answer 1

    The BackColor property refers to the so-called AmbientProperties . See Remarks .

    Its value is set the same as that of the parent control (this is done to simplify the design: we add a control - its parameters are determined automatically).

    As long as the control is not added to the parent, it makes no sense to change this property. It needs to be changed after adding.

     Controls.Add(buttonDyn); buttonDyn.BackColor = Color.Chartreuse;