|
-
April 11th, 2009, 05:31 AM
#1
Random button color ?
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
-
April 11th, 2009, 11:07 AM
#2
Re: Random button color ?
You'll have to add your own handlers for Click events, but here ya go:
Code:
// 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.
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|