I placed custom buttons on my form by using a for loop with code like this:
// pass control array to each button
this.myButton = new CustomButton.MyButton(this.Controls);
this.Controls.Add(this.myButton);
this.myButton.Location = new System.Drawing.Point(t,s);
this.myButton.Size = new System.Drawing.Size(50,50);
this.myButton.Text = "";
But how can I reference each individual button during the click operation?
Answer: I wrote code to handle the Click event in the CustomButton.cs class, since this code is essentially the same for every button.
System.Windows.Forms.Control.ControlCollection
When the player clicks a button, one of the 25 button objects gets its Click handler called. That button can tell which one it is by it's index in the form's control array. (By the way, I had to pass a reference to the form's control array to every button object in its constructor. The button constructor just stashes the reference in a local variable for use later during clicks). The form control array is:
Then I could have code like this in the button click handler:
if (myControlReference!=null)
{
myIndex = myControlReference.IndexOf(this);
// now I know who I am and can also calculate
// the index of neighboring buttons whose color
// I must change; and I used their index to do it
}
For example, I can reach the preceding button object (assuming this is not the very first of the buttons) with syntax like
myControlReference[myIndex-1];
I also push myIndex onto a stack (which has to be accessible in a "global" class rather than from within one button object). When the user wants to undo a move, I pop the top index from the stack and use it with the above syntax to tell the button to execute it's Click event (call the Click handler explicitly).I also needed a method in my button class to toggle the color. Neighbors call this to change the color of just that button.