Click to See Complete Forum and Search --> : Random button color ?


Angel_One
April 11th, 2009, 05:31 AM
Hi,

I've just begun with C# and I've encountered a problem...

I've got 25 buttons on my windows form, they all have black background... My objective is to randomly assign them one of 2 colors (black, white), when my application starts. How can I solve my problem? Could you help me?



Thanks,


Gregory

mariocatch
April 11th, 2009, 11:07 AM
You'll have to add your own handlers for Click events, but here ya go:


// Seed random number generator.
Random ranNum = new Random();

// Fill flow with buttons.
for (int i = 0; i < 25; i++)
{
// Create button and add to flow container.
Button newButton = new Button();
newButton.Parent = flowLayoutPanel1;

// Set each button's BackColor to Black or WhiteSmoke.
// The color is decided based off the Random class.
// If Random.Next == 0, then color == Black
// If Random.Next == 1, then color == WhiteSmoke
// Random.Next excludes the upper bound, so this gets a random number
// between 0 and 1, not 0 and 2.
newButton.BackColor = (ranNum.Next(0, 2) == 0) ? Color.Black : Color.WhiteSmoke;

// TODO:
// Add code for handling Click events from each button.
}