tags:

views:

65

answers:

3

I have a C# button, let's say 'ON/OFF':

I want to change 'OFF', when we first click it and run buttonOFF() When we click again, it changes to 'ON' and run buttonON()

and so on..

What's the correct way to do that? Can I do it all in one onClick event? peace of small example would be useful. Thanks !

+3  A: 
private void buttonON()
{
    // Magic here
}

private void buttonOFF()
{
    // Magic here
}

protected void button_click(object sender, EventArgs e)
{
    if ( button.Text == "ON" )
    {
        button.Text = "OFF";
        this.buttonOFF();
    }
    else
    {
        button.Text = "ON";
        this.buttonON();
    }
}
Vilx-
thanks! I though I should smth with -+ removing and ++ adding events recursively. But this will work
Stewie Griffin
But if i don't want change Text of my button?
Pavel Belousov
This might be improved by leveraging a state variable instead of checking the button text; but if you don't have i18n to worry about, this is definitely clear and concise
Michael Haren
If you decide to change text of the button you need to remember to change it in the code too
Giorgi
what to do, if instead using button, I am using ImageButton, where button.text is unavailable ?
Stewie Griffin
@Tomasusa - change the image? Honestly, it's up to you. Modify the button as you want. Is the pattern here really so non-obvious?
Vilx-
+4  A: 

You might best using this method. Using a checkbox with a button appearance

CheckBox checkBox1 = new System.Windows.Forms.CheckBox(); 
checkBox1.Appearance = System.Windows.Forms.Appearance.Button; 
Dean
A: 

Although the solution works, I think there's an issue with the UI. Consider this:

As a user I'm looking at a button, the button says "Off". Does this represent state or action? Is it on and by clicking I'll turn it off? Or is it off and by clicking I'll turn it on? Also, what am I turning on/off? The UI is somewhat ambiguous unless I have experience and have learned what it means.

However, if you were to use something like the checkbox appearance suggested by Dean and label the button (checkbox), say, "Engine", both the state and the purpose are clear:

alt text

Ragoczy
on/off was just an example .. more informative text will be on the button. Thanks anyway, good catch here
Stewie Griffin