The code in the button1_Click event uses the Font Dialog control and the richTextBox1
control to change the font of selected text in the text box. The button2_ Click
event performs a similar task to the button1_click event: It uses the ColorDialog
control to change the color of the text in the text box.
The button3_Click event performs a simple databasesave routine. This code uses
the RichTextBox control's Rtf property to convert the unformatted text to RTF
text, then passes it to the ADO.NET command object for update into the database.
Because the table has only one row, the UPDATE statement doesn't need a WHERE
clause.
The button4_Click event loads the RTF data that was saved to the database (after
the color and font were changed) into the text box. This code again uses the
Rtf property, this time associated with richTextBox2, to display the retrieved
data with formatting intact. The code uses a SELECT TOP 1 statement to load
the first row from the table.
Step 4: build and run the Project
Your final step is to build and then run the project. You can build a project
either by clicking the green Play button on the main toolbox or pressing F5
to start the application in runtime mode. After you've built the application,
you should see a dialog box similar to that in Figure
1 containing the unformatted sentence "The quick brown
fox jumps over the lazy dog" in the Enter Rich Format Text box. Let's test
the application by formatting the text, saving it to the database, and retrieving
the formatted text from the database. To do so, perform these steps:
- Highlight the words "quick brown" and change the font by clicking the font
button. Select an italics font and font size (I used Brush Script MT, Italic,
14).
- Highlight the words "over the" and change the color to red by clicking
the Color button and choosing the color.
- Click the Save button to save the text to the database.
- Click the Load button to load the saved data from the database into the
Text from Database text box.
As you can see, when you run the application for first time, the retrieved
data isn't formatted and the Text from Database text box is empty. After
you perform the previous steps, the result in both textboxes will look same.
A Handy Tool
Collecting RTF data from a user and storing it in a SQL Server 2005 database
table is a simple process, with the help of my C# script. The ability to store
and retrieve formatted data will save you and your end users time, for example,
by avoiding the need to reformat database data that's merged into a form.