2
votes

I have a set of radio buttons, and two of them need to prompt the user with a confirmation dialog before allowing the value to change. To do this, I handle the click event and set the AutoCheck property to false on each of these radio buttons. However, the previously selected RadioButtons are no longer unchecked when I set the check property to true on the clicked RadioButton.

Right now I'm just looping through the controls on this panel and making sure none of the other RadioButtons are checked, but is there a more efficient way to do this?

1
what's wrong with AutoCheck?King King
You can't gracefully cancel the checked changed event, I'd have to keep track of what the last selected radio button was with a member variable. By manually handling the click event for this, I can more gracefully "Cancel" the CheckedChanged event by making sure the RadioButton values don't even change in the first place.Bender the Greatest
That's just a consequence of setting AutoCheck to false, now it is up to you to control the check state. The approach is fairly questionable, radio buttons should be simple. Consider doing the confirmation in the OK or Apply button Click event handler.Hans Passant
The UI automatically performs work when the checked state is changedBender the Greatest

1 Answers

1
votes

You can use some variable to store the last checked radiobutton:

//first, you have to set the lastChecked = radioButton1 (or another of your radioButtons)
RadioButton lastChecked;
//Click event handler used for all the radioButtons
private void RadiosClick(object sender, EventArgs e)
{
   RadioButton radio = sender as RadioButton;
   if (radio != lastChecked){
      radio.Checked = true;
      lastChecked.Checked = false;
      lastChecked = radio;
   }
   //else radio.Checked = !radio.Checked;     
}

If you want to allow user to uncheck the radio (a very strange behavior), just remove the // before the else clause in the code above.