I am trying to change the text of a Button every time its clicked.
Button Starts as "ON". When I click it the first time it should change to "OFF", and when I click it again, it should change back to On.
I understand how to change it to "OFF" when clicked, but I am unsure as to how to check for a secondary click so I can change the text back to "ON".
Here is my code so far:
private void OrdersButton_Click(object sender, EventArgs e)
{
OrdersButton.Text = " Turn Orders Off";
}
To change the text of a button on click: Add a click event listener to the button. Use the textContent property to change the button's text. For example, btn. textContent = 'Button clicked' .
To change a button's text on click in React:Track the text of the button in a state variable. Set the onClick prop on the button element. When the button gets clicked, update the state variable.
Python Tkinter – Change Button Text Dynamically You can change the text property of Tkinter button using the reference to the button and 'text' option as index. Now bText contains the text of the button .
Right click on the function name and select Rename. The name will be highlighted (it's green on my system, see picture below). Edit the name and then hit the Apply button. The button's click event will correctly point to the newly renamed method.
Try
private void OrdersButton_Click(object sender, EventArgs e)
{
if (OrdersButton.Text == "Turn Orders On")
{
OrdersButton.Text = "Turn Orders Off";
}
else if (OrdersButton.Text == "Turn Orders Off")
{
OrdersButton.Text = "Turn Orders On";
}
}
Hope this helps.
I can see several possible problems with that and can offer a more object oriented solution: Adding a property that keeps track of the current "state":
private bool _IsOn;
public bool IsOn
{
get
{
return _IsOn;
}
set
{
_IsOn = value;
OrdersButton.Text = _IsOn ? "On" : "Off";
}
}
and using the event handler to simply toggle the property:
private void OrdersButton_Click(object sender, EventArgs e)
{
IsOn = !IsOn;
}
That way it's easier to access the information later on and you can easily replace on/off with whatever you like - even globalize/localize it if required. I think it's a very bad programming practice to have code depend on the text that is on the display...
EDIT: Also, wouldn't using a checkbox or a togglebutton make more sense? Other than the visual representation being different, it does what you want out of the box...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With