I’m coding a random seat generator for an airplane and I’m using a FOR loop in it. The thing is, the occupied seats only show when everything is done. What I would like it to do was in each iteration, show the random seat selected. How would one do that?
Here’s the code I’m using. The plane has 118 seats and I have a picturebox named “img_Seat_X” for each one of them. I know there’s a better way to this, but that’s I could think in a quick hour. Thanks in advance!
private void btn_WeightBalance_Populate_Click(object sender, EventArgs e)
{
int passengers = Convert.ToInt32(txt_WeightBalance_Passengers.Text);
List<int> seats = new List<int> { }; numberofSeats = 119;
if (rdb_WeightBalance_190.Checked == true)
numberofSeats = 107;
for (int x = 0; x < Passengers; x++)
{
int randomNumber = RandomNumber(1, numberofSeats);
if (seats.Contains(randomNumber))
x--;
else
{
seats.Add(randomNumber);
Control[] seat = this.panWeightBalance.Controls.Find("img_Seat_" + randomNumber, true);
seat[0].Visible = true;
seat[0].Refresh();
}
}
}
Figured it out! A simple Refresh() in each iteration did the job! I also replaced the while loop with an if statement.
First, required reading: The Windows Message Loop
@rice pointed out my obvious error, sorry for leading you down the wrong path, thanks rice.
Anyway, you can perform the work in a separate thread and post updates to the UI trhead using the BackgroundWorker class. Here is a simple example which updates a label on a form 100 times in response to a button click: