Reputation: 37
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;
Upvotes: 0
Views: 25098
Reputation: 6304
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;
Upvotes: 4
Reputation: 1867
if( label.BackColor == Color.Red)
{
label.BackColor = Color.Transparent;
}else
{
label.BackColor = Color.Red;
}
Upvotes: 0
Reputation: 10622
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.
Upvotes: 0
Reputation: 2780
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;
}
}
Upvotes: 1