简体   繁体   中英

Toggle a button's text from “On” to “Off” when clicked (Visual C++)

I was given a small task to simply make a button's text toggle "On" and "Off" when you clicked on it - it already starts with the text "Off" as it hasn't been pressed yet, but when you click it changes to "On". On each alternating click afterwards, the button's text would ideally keep changing from "On" to "Off". In my case I thought a simple boolean variable would be the solution as On and Off can be treated as True or False, but not to be...

Anyway here's the code for the button's handler I've got so far:

private: System::Void toggleButtonText_Click(System::Object^  sender, System::EventArgs^  e) 
    {
      static bool isOn = true;
      if(isOn == false)
      {
       toggleButtonText->Text = "Off";

      }
      else
      {
      toggleButtonText->Text = "On";
      }

}

As you can see, the name of the button is "toggleButtonText". In the InitializeComponent(void) method, this line enables the default text to "Off":

this->toggleButtonText->Text = L"On";

Looking at the rest of my tasks, getting this right will give me enough clues to attempt them on my own instead of spending ages on endless Google searches.

You need t toggle the flag each time you click the button. You can also greatly reduce the size of your code if you use the ?: operator:

static bool isOn = true;
toggleButtonText->Text = isOn ? "On" : "Off";
isOn = !isOn;

You have to update your variable state after toggling the text

  static bool isOn = true;
  if(isOn == false)
  {
     toggleButtonText->Text = "Off";
  }
  else
  {
     toggleButtonText->Text = "On";
  }
  isOn = !isOn; //toggle the flag too

Using static variable here is an extremely crappy solution. For example, if you change button's state programmatically the static variable will be out of sync with the actual press state.

Why not get toggle state from the button itself? Here's anwser how to add actual toggle button in the Windows Forms. After that you can modify the method the following way:

System::Void toggleButtonText_Click(System::Object^  sender, System::EventArgs^  e) 
{
    CheckBox^ button = (CheckBox^)sender;
    if (button->Checked)
    {
        button->Text = "On";
    }
    else
    {
        button->Text = "Off";
    }
}

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