I have never really written any document editing type of functionality in my software. Today I needed to and got stuck on doing something like changing some highlighted text in a RichTextBox control to bold or removing the bold if it exists.
I started just playing with the classes and quickly realized the Bold property is readonly.
The documentation I found was showing me how to set a font anew:
RichTextBox1.SelectionFont = New Font("Tahoma", 12, FontStyle.Bold)
Which meant getting the existing font family and size and putting those into the first two parameters. It also meant I couldn't remove the Bold without removing other styles such as Italics.
Luckily I have a copy of Charles Petzold's VS2005 Windows Forms book and knowing that he is totally into that kind of stuff, I was confident I'd find code to do it. And of course I did!
It played around with how to translate the C# into VB, but since I didn't understand how it was working, I went down the wrong path. Thanks to some help from Bill McCarthy, I've got it worked out.
Here's how to handle this on a button.click event:
Private Sub FontBold_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FontBold.Click
If rtb.SelectionFont.Bold Then
rtb.SelectionFont = _
New Font(rtb.SelectionFont, rtb.SelectionFont.Style And Not FontStyle.Bold)
Else
rtb.SelectionFont = _
New Font(rtb.SelectionFont, rtb.SelectionFont.Style Or FontStyle.Bold)
End If
End Sub
The syntax for doing the key part of this in C# (which is what is in Charles' book) looks like this:
to add the bold formatting:
rtb.SelectionFont =
new Font(rtb.SelectionFont, rtb.SelectionFont.Style | FontStyle.Bold)
to remove the bold formatting:
rtb.SelectionFont =
new Font(rtb.SelectionFont, rtb.SelectionFont.Style & ~FontStyle.Bold)
I definitely prefer the obviousness and simplicity of VB's syntax to C#'s usual hieroglyphics. (Dear Shacknews readers: it's a joke!)But that's why I keep books like Charles' and the O'Reilly C# & VB.NET Conversion Pocket Reference handy (which I would have been smart to actually look at to do a direct translation of the C#, rather than attempting my own interpretation.)
I'm sure today, Charles would just say to use WPF since you could make the change declaratively and not have to deal with all of that crazy OO coding. ;-)