Reputation: 529
My program makes labels bold, italic, or underline depending on the button clicked. But when I attempt to have both effects at once the first fades off.
Private Sub bold_Click(sender As Object, e As EventArgs) Handles bold.Click
Dim con4 As Control
For Each con4 In Me.Controls
Select Case con4.Name
Case "Label1"
If con4.Font.Bold = False Then
con4.Font = New Font(con4.Font, FontStyle.Bold)
Else
con4.Font = New Font(con4.Font, FontStyle.Regular)
End If
Case "Label2"
If con4.Font.Bold = False Then
con4.Font = New Font(con4.Font, FontStyle.Bold)
Else
con4.Font = New Font(con4.Font, FontStyle.Regular)
End If
...
End Select
Next
End Sub
This code goes up to Label24.
So I use the same procedure for 3 different buttons and they get me my result. But attempting to have 2 effects together overrides the previous one.
Thanks guys.
Upvotes: 0
Views: 17085
Reputation: 22457
You override the font style with the very next test because you inspect-and-set all conditions only one at a time.
Combine the tests for each label once, then pick the right font:
If con4.Font.Bold = False Then
If con4.Font.Italic = False Then
con4.Font = New Font(con4.Font, FontStyle.Bold Or FontSryle.Italic)
Else ' not italic
con4.Font = New Font(con4.Font, FontStyle.Bold)
End If
Else ' not bold
If con4.Font.Italic = False Then
con4.Font = New Font(con4.Font, FontStyle.Italic)
Else ' not italic
con4.Font = New Font(con4.Font, FontStyle.Regular)
End If
End If
As you can see, this gets unwieldy very fast; especially if you are repeating the same code for 24 labels. So, step #1 would be to make this sequence a function.
Step #2 is to get rid of all those comparisons - adding Underline would add yet another level of if..else..end if
for all of the separate cases! You can combine FontStyle
bits with an Or
to form the final value, and only then set it:
fontstyle = FontStyle.Regular
If cond4.Font.Bold = False Then
fontstyle = fontStyle.Bold
End If
If cond4.Font.Italic = False Then
fontstyle = fontstyle Or fontStyle.Italic
End If
If cond4.Font.Underline = False Then
fontstyle = fontstyle Or fontStyle.Underline
End If
target.Font = New Font(con4.Font, fontstyle)
(This may not entirely be the correct syntax, but the general idea should be clear.)
Upvotes: 4