简体   繁体   中英

What is the proper way to manually check and uncheck a RadioButton when the AutoCheck property is set to false in C#?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM