I create buttons in my application by:
List<Button> btnslist = new List<Button>();
for (int i = 0; i < nbrofbtns; i++)
{
Button newButton = new Button();
btnslist.Add(newButton);
this.Controls.Add(newButton);
newButton.Width = btnsidelength;
newButton.Height = btnsidelength;
newButton.Top = btnsidelength
* Convert.ToInt32(Math.Floor(Convert.ToDouble(i / Form2.puzzlesize)));
newButton.Left = btnsidelength
* Convert.ToInt32(
Math.Floor(Convert.ToDouble(i))
- Math.Floor((Convert.ToDouble(i))
/ (Form2.puzzlesize)) * (Form2.puzzlesize));
newButton.BackgroundImage = Lights_out_.Properties.Resources.LightsOutBlack;
newButton.Tag = (i+1).ToString();
newButton.Click += new EventHandler(Any_Button_Click);
Then I have a method for when any of the buttons are clicked.
void Any_Button_Click(object sender, EventArgs e)
{
//the variable b has all the insformation that the single button had itself.
Button b = (Button)sender;
if (b.BackgroundImage == Lights_out_.Properties.Resources.LightsOutBlack)
{
MessageBox.Show(b.Tag.ToString());
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
btnslist[Convert.ToInt32(b.Tag)].BackgroundImage =
Lights_out_.Properties.Resources.LightsOutWhite;
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
}
else
{
MessageBox.Show("b.backgroundimage != lightsoutblack. Backgroundimage = "
+ b.BackgroundImage.ToString());
}
}
How do I change the data in the actual button (then said button is clicked)? I want specificly to change the backgroundimage. How could I do this?? (I also need to change the backgroundimage of some other buttons created by the code.)
The sender object is the button:
... so you should be able to change properties on it directly:
PS: I don't think this is necessary, but if the button is not updated directly, you might try to using
b.Refresh()
to let it know something has changed.You're handling
Click
event of every button you've created - andsender
inAny_Button_Click
is actually the button was clicked.So just change
b.BackgroundImage
to whatever you need.