Search code examples
c#event-handlinglabelbackcolor

Change label backcolor when click


Hello guys i have a easy problem here, if i click the label1 it will change back Color to Red but my default Back Color is transparent.

   private void label_Click(object sender, EventArgs e)
   {

       label1.BackColor = Color.Red;
   }

   private void label2_Click(object sender, EventArgs e)
   {
       label2.BackColor = Color.Red;
   }

what if i click the label again i want it to change color to transparent, how do i code that? Thank you in advance! :D

label.BackColor = Color.Transparent;

Solution

  • You just need to flip the color based on its current value. That can be done by doing:

    label1.BackColor = label1.BackColor == Color.Red ? Color.Transparent : Color.Red;
    

    The above is a conditional operator and is basically just shorthand for an if/else statement,

    if (label1.BackColor == Color.Red)
        label1.BackColor = Color.Transparent
    else
        label1.BackColor = Color.Red;