I'm trying to force the user to select a rabiobutton before being allowed to move next. I made the "Next" button invisible but I have like 10 radiobuttons that must be verified if any of them are checked. By definition, only 1 radiobutton can be checked. My code looks something like this:
b1.Text = "Next";
b1.Parent = fpn1;
fpn1.Controls.Add(b1);
b1.Dock = DockStyle.Bottom;
b1.BackColor = Color.LightGray;
b1.Visible = false;
RadioButton rb;
while (b1.Visible == false)
{
MessageBox.Show("LOOOL");
//Thread.Sleep(5000);
rb = fpn1.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
if (rb != null)
{
b1.Visible = true;
}
}
So while none of my radiobuttons is clicked, b1 is invisible. The problem is... this going into an infinite loop. The user can't even pick any button anymore cause the page won't load. Any idea of a get-around?
What else can I do to have the wanted result?
Infinite loops are really good at blocking an application from doing anything. Essentially, you're thinking about it backwards. You're thinking:
Keep making the button invisible until something happens.
Why? Once you make the button invisible, it's going to stay that way until you change it. So, instead, think of it this way:
Make the button visible when something happens.
In this case "something happens" is a user changing the values of your radio buttons. So you want a handler for that event:
private void radioButton_CheckedChanged(Object sender, EventArgs e)
{
// your logic here
}
You can use the forms designer to assign this function to all of the CheckedChanged
events of the various radio buttons, so they all use the same handler.
Then what would "your logic" be? Well, really, that's up to you. It sounds like you want to wait until several different radio button groupings have been selected? So you'd build some conditional based on that. At a high level, that would semantically look like this:
if (allRadioButtonsSelected())
b1.Visible = true;
If the line of code you have does what you want:
rb = fpn1.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked)
then you could even just use that:
if (fpn1.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked) != null)
b1.Visible = true;
Though it doesn't entirely sound like that's what you're looking for, since that's going to tell you if just one radio button is checked. But I may have misunderstood you on that, so it's up to you.
The point is, don't keep looping and blocking the thread while checking to see if something has happened. Because while you're blocking the thread, it will never happen. Instead, use event handlers to respond to events when they happen.