delegate button1.MouseClick event than changes its control properties

311 Views Asked by At

hi this is my first post to please bear with me. ;)

I have a small class that generates buttons when an event occurs. What i cannot seem to achieve is add code to the delegate mybutton_MouseClick that changes the color of an individual generated button when its cliked.

So im looking for some code that would do: mybutton.BackColor = Color.Red;

namespace test_addObject
{
    public partial class Form1 : Form
    {
        ButtonCreation bc = new ButtonCreation();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bc.createButton();
        }
    }

    public class ButtonCreation
    {
        Random rdm = new Random();

        public void createButton()
        {
            Button mybutton = new Button();
            Form1.ActiveForm.Controls.Add(mybutton);

            mybutton.Location = new Point(
                rdm.Next(Form1.ActiveForm.Width - mybutton.Width),
                rdm.Next(Form1.ActiveForm.Height - mybutton.Height));

            //mybutton.BackColor = Color.Red;   //this will generate them red.
            mybutton.MouseClick += new MouseEventHandler(mybutton_MouseClick);
        }

        void mybutton_MouseClick(object sender, MouseEventArgs e)
        {
            //some code here to change the generated button color when they are clicked individually.
            //...
            //...
        }
    }
}
1

There are 1 best solutions below

2
On BEST ANSWER

Here: void mybutton_MouseClick(object sender, MouseEventArgs e) sender is actually button was clicked.

So just cast sender to Button and you will be able to set its backcolor.

Like this:

var mybutton = sender as Button;
mybutton.BackColor = Color.Red