Reputation: 37
I want to create a toggle button but it stays at On. How do I toggle the button from on to off.
private void Form2_Load(object sender, EventArgs e){
Button button = new Button();
button.Location = new Point(200, 30);
button.Text = "Off";
this.Controls.Add(button);
if (button.Text != "On")
{
button.Text = "On";
button.BackColor = Color.Green;
}
else if (button.Text == "On")
{
button.Text = "On";
button.BackColor = Color.Red;
}
}
Upvotes: 1
Views: 318
Reputation: 186668
It should be something like this: creation + changing state on click:
private void Form2_Load(object sender, EventArgs e){
// Initial creation
Button button = new Button() {
Location = new Point(200, 30),
Text = "Off",
BackColor = Color.Red,
Parent = this,
};
// Click handle, let it be lambda
// Toggle on click (when clicked change On -> Off -> On ...)
button.Click += (s, ev) => {
Button b = sender as Button;
if (b.Text == "On") {
// when "On" change to "Off"
b.Text = "Off";
b.BackColor = Color.Red;
}
else {
b.Text = "On";
b.BackColor = Color.Green;
}
};
}
Upvotes: 0
Reputation: 43876
You need to put the code to change the button's appearance in the Click
event handler of that button:
private void Form2_Load(object sender, EventArgs e){
Button button = new Button();
button.Location = new Point(200, 30);
button.Text = "Off";
this.Controls.Add(button);
// subscribe to the Click event
button.Click += button_Click;
}
// the Click handler
private void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button == null) return;
if (button.Text != "On")
{
button.Text = "On";
button.BackColor = Color.Green;
}
else if (button.Text == "On")
{
button.Text = "Off";
button.BackColor = Color.Red;
}
}
And note that in your else
block you set the wrong text. Change it to "Off"
.
Upvotes: 2
Reputation: 8111
You are always setting the text to On
. Change your else block:
else if (button.Text == "On")
{
button.Text = "Off"; // here !!!
button.BackColor = Color.Red;
}
Or use this solution to create a ToggleButton: ToggleButton in C# WinForms
Upvotes: 1