سؤال

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;
هل كانت مفيدة؟

المحلول

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;

نصائح أخرى

Why don't you just add an if statement:

private void label_Click(object sender, EventArgs e)
{
    if(label1.BackColor == Color.Red)
    {
         label1.BackColor = Color.Transparent;
    }
    else
    {
        label1.BackColor = Color.Red;
    }
}
  private void label_Click(object sender, EventArgs e)
   {
       Label label1 = (Label)sender;
       if (label1.BackColor == Color.Red)
            label1.BackColor = Color.Transparent;
       else
            label1.BackColor = Color.Red;
   }

by using the line Label label1 = (Label)sender; You can apply the same event for all your labels.

if( label.BackColor == Color.Red)
{
     label.BackColor = Color.Transparent;
}else
{
    label.BackColor = Color.Red;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top