Home > Enterprise >  C# How to randomize a color on buttons in Form 2 from clicking a button on Form1
C# How to randomize a color on buttons in Form 2 from clicking a button on Form1

Time:12-03

I am building a C# movie theater program. On Form1, when clicking on "Reserve" button I want the 21 buttons on Form 2 to randomly change 6 seats to "Red". I would like for it to be different seats every time the "Reserve" button is pressed on Form 1.

Here is the code I am trying to make work.

Random random = new Random();

private Color GetRandomColor()
{
    return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}

private void reserve_button_Click(object sender, EventArgs e)
{
    button1.BackColor = GetRandomColor();
    button2.BackColor = GetRandomColor();
    button3.BackColor = GetRandomColor();
    button4.BackColor = GetRandomColor();
}

enter image description here

enter image description here

CodePudding user response:

Well, you should take 6 random seats which are not Red and color them red. Assuming that you use Winforms:

Form2 which shows the seats:

using System.Linq;

  ... 

public bool MakeReservation(int count) {  
  // Buttons to exclude from being painted into red:
  HashSet<Button> exclude = new HashSet<Button>() {
    //TODO: put the right names here
    btnBook,
    btnClear,  
  };

  var buttons = Controls                             // All controls
    .OfType<Button>()                                // Buttons only
    .Where(button => button.BackColor != Color.Red)  // Non red ones
    .Where(button => !exclude.Contains(button))      // we don't want some buttons
    .OrderBy(_ => random.NextDouble())               // In random order
    .Take(count)                                     // count of them
    .ToArray();                                      // organized as an array

  //TODO: you can check here if we have 6 buttons, not less  
  if (buttons.Length < count) {
    // Too few seats are free 
    return false; 
  }

  // Having buttons selected, we paint them in red:
  foreach(var button in buttons)
    button.BackColor = Color.Red;

  return true;
}

When Form1 either opens a new Form2 or finds existing one:

private void reserve_button_Click(object sender, EventArgs e) {
  var form = Application
    .OpenForms
    .OfType<Form2>()
    .LastOrDefault();

  if (form == null) 
    form = new Form2();
  
   form.Show();
   //TODO: put the actual number instead of 6
   form.MakeReservation(6);
}
  • Related