Search code examples
c#labeleventhandler

C# label should do diffrent things when clicked


I need a label which does something different with every click.

 private void open_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            builder = new StringBuilder(4);
            builder.Append(zahl1.Text);
            builder.Append(zahl2.Text);
            builder.Append(zahl3.Text);
            builder.Append(zahl4.Text);

            code = builder.ToString();

        }
        if( code== setCode)
        {
            openAndClose.BackColor = Color.DarkGreen;
            setNewCode.Visible = true;

        }
        else
        {

        }

    }

With the first click the BackColor gets green and the visible is true. And now it should go back in the start position if I click it again. That means BackColor should be red and the visible should be false. Can I do this wth a second Eventhandler?

openAndClose.Click += new EventHandler(open_Click);

Thanks


Solution

  • You could simply do the following:

    if(code == setCode)
    {
        openAndClose.BackColor = openAndClose.BackColor == Color.DarkGreen ? Color.Red : Color.DarkGreen;
        setNewCode.Visible = !setNewCode.Visible;
    }
    

    The first part toggles the color between green and red, and the second part toggles the visibility.