Click here to Skip to main content
Email Password   helpLost your password?

Note: This control is totally standalone. If you've downloaded it before, please do again as I accidenly left some third party references in the demo project.

Introduction

This article was prompted by comments about Rich Parson's RichTextBoxExtended Control. This is a very useful control that includes a tool bar to augment the existing RichTextBox control into a word processor.

The comments from users were very positive, but there was a desire to be able to set the content of a rich text control via the Rtf property so it can be persisted in the form design. Secondly, for cases where the content is being edited at runtime, it makes sense to be able to data bind to the Rtf property. This article explains how to do both of these so you can build fully functional Rich Text forms with a minimum of effort.

Minor Changes

I made a few minor changes unconnected with persistence that I hope won't be controversial.

Gotyas

When working with the existing RichTextBox control, there are two "features" that can catch you out. Firstly, as mentioned by Rich, if you set Rtf before the form initialization, the RichTextBox control will sometimes lose its formatting and just display plain text. Secondly, there is a bug in the Rtf property where it sometimes returns a null character as the very last character in the string. This causes no problems with designer form persistence when the RichTextBox control has a short content. However, once the content gets longer, the designer serialization code has a nervous breakdown and messes up the job of breaking the string into multiple lines. (Possibly, this is why MS made the Rtf property unavailable as standard in the property editor in Visual Studio.) This caused me more than a little bit of grief but it needn't cause you any if you use the RichTextBoxExtended included with this article.

How to get the Rtf property to work

In order for consumers of the Rtf property to be aware of changes, there needs to be a property change event called RtfChanged. This event will automatically be hooked to handle data binding or form designer serialization.

We must ensure that this event is triggered whenever the content has been updated. The obvious case is when the user has updated the content directly. This, we check in a Leave event handler. The Rtf property may be set directly so we need to trigger our event here also. Finally, Rtf could change indirectly as a result of a change to the Text property.

[Category("Property Changed")]
public event EventHandler RtfChanged;

[
    System.ComponentModel.Description("Contents in Rtf format"),
    RecommendedAsConfigurable(true),
    Category("Data"),
    Bindable(true),
    Editor(typeof(Design.RichTextBoxExtendedEditor), 
           typeof(System.Drawing.Design.UITypeEditor))
]
public string Rtf
{
    get
    {    return rtb1.Rtf;
    }
    set
    {    rtb1.Rtf= value;
        if (RtfChanged!=null)
            RtfChanged(this,EventArgs.Empty);
    }
}
#endregion

private void rtb1_TextChanged(object sender, System.EventArgs e)
{
    if (RtfChanged!=null)
        RtfChanged(this,EventArgs.Empty);
}

private void rtb1_Leave(object sender, System.EventArgs e)
{
    if (this.rtb1.Modified && RtfChanged!=null)
        RtfChanged(this,EventArgs.Empty);
}

Providing a Property Editor for the Rtf Property

There's a pleasing recursion here, as the ExtendedRichText control is used to edit its own Rtf property.

Implementing a property editor is accomplished by adding the Editor attribute to the Rtf property. This attribute specifies which UITypeEditor to invoke. The implementation of this UITypeEditor is fairly simple as shown below:

class RichTextBoxExtendedRtfEditor:System.Drawing.Design.UITypeEditor
{
    public override System.Drawing.Design.UITypeEditorEditStyle 
                    GetEditStyle(ITypeDescriptorContext context)
    {
        if (context==null)
            return base.GetEditStyle(null);
        return System.Drawing.Design.UITypeEditorEditStyle.Modal;
    }

    public override object EditValue(ITypeDescriptorContext context, 
                           IServiceProvider provider, object value)
    {
        if (context!=null && provider!=null)
        {
            IWindowsFormsEditorService edSrv= 
              (IWindowsFormsEditorService)
              provider.GetService(typeof(IWindowsFormsEditorService));
            if (edSrv!=null)
            {
                RichTextBoxExtendedRtfEditorForm dialog= 
                  new RichTextBoxExtendedRtfEditorForm();
                if (value is String)
                    dialog.Value= (string)value;    
                if (edSrv.ShowDialog(dialog)==
                         System.Windows.Forms.DialogResult.OK)
                    value= dialog.Value;
                dialog.Dispose();
                dialog= null;
            }
        }
        return value;
    }
}

Data Binding and Automatic Binding

Once persistence of Rtf has been implemented for designer serialization, it will automatically work for data binding. The image of the included demo application shows two RichTextExtended controls - one is read only and is persisted in the form design. The other is editable and is data bound and persisted in a DataSet at runtime. To keep the sample simple to install, this DataSet is persisted in a text file as XML. In a real world application, persistence would probably be to a database and it works fine this way. Just make sure your database columns are large enough as the formatting information makes rich text bigger than you might expect.

A standalone solution (RichTextExtended.sln) has been provided in the demo project. If you use AgileStudio, a solution has also been included (RichTextBoxExtended2.sln) that implements automatic binding. In fact, I used this mechanism to knock together the demo app really quickly.

Conclusion

This modified RichTextBoxExtended now has a property editor to allow you to persist Rich Text as part of the form design. It also supports data binding to allow the editing of Rich Text from a data source at runtime. Now, you can knock together rich text apps without having to hand code your Rtf assignments.

However, if you want to go one step further, the automatic binding in AgileStudio makes it really fly as this automatically builds the SQL Server database and builds the stored procedures, typed datasets, and bindings when you just drop the ExtendedRichText control on the form.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralCant get the plain text out from it.
ivanchain@hotmail.com
7:06 13 Apr '09  
I have set the RTF, and it shows well.
But when I try to get the RTF out from the controls.text, I found the text property is always NULL.

So if we could not get the plain text out, how we could show the text on another part of the application?

yours,
Ivan

123

GeneralHow I Can change color TextLink in RichtextboxEx
Member 4722227
5:17 12 Dec '08  
I used hepl from CodeProject is "Links with arbitrary text in a RichTextBox". But i can't change color TextLink into Red. Default is blue
Please help me exaple code.
Email: itbinh75@gmail.com

Thank you and Regard

binhhu

QuestionWant to send RichTextBox Data via E-mail
m_salman
0:24 27 Sep '07  
hi
I have read your article its really help full but i have being in problem and that i have made a windows application and want to send the rich text data via e-mail but when i read data from the rich text box and send it via e-mail as body it doesn't send the data in the format it is shown in rich text box kindly guide me how i solve this issue.
i am using this technique
milmessage.body = richtextbox.text;
smtpclient.send(mailmessage);

regards
Salman
AnswerRe: Want to send RichTextBox Data via E-mail
Declan Brennan
1:23 27 Sep '07  
Hi Salman,

The Text property only gives you plain text. If you want to get RTF out you need to use the Rtf property.

Secondly by default SMTP messages are sent as plain text. If you want to send some other format, you need to use mailmessage.AlternateViews or send the RTF as an attachment.

One word of caution though, RTF is not a common format for mail messages. Not all clients will understand it. Rich mail tends to be sent using a variation of HTML.

All the best,

Dec.

Declan Brennan Chief Architect
Sekos Technology Ltd
www.sekos.com

QuestionRe: Want to send RichTextBox Data via E-mail
m_salman
1:29 27 Sep '07  
thanks but the thing is the data i got from the rich text box is like "{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}" so can u guide me that how i convert this in to html as i am new in this field
i shall be very gratefull
regards
salman
GeneralThis needs 3rd party add ons to use
Medmerd
9:16 16 Mar '07  
This control can not be used unless you have the NON FREE Visual Studo comonent from sekos.com. I dont use this control why would you assume everone else does? Such a waste of time for this to even be here.
GeneralRe: This needs 3rd party add ons to use
Declan Brennan
4:37 20 Mar '07  
Appologies for shouting but:
THIS IS NOT THE CASE.

The code does NOT require Visual Studio. It is entirely stand-alone (although it is possible to optionally use it with Visual Studio.)

The whole purpose of Code Project is to share free code with no strings attached and I, like thousands of others, go to huge efforts- unpaid and occasionally unappreciated, to do this. This makes it very discouraging to get incorrectly flamed in this manner.

It would be great if you would post a retraction, when you get a chance to verify that I'm telling the truth. Otherwise your comment may cause confusion.

Thanks,

Declan.





Declan Brennan Chief Architect
Sekos Technology Ltd
www.sekos.com

QuestionPrint and Print Preview Contents of RTF
NaughtyZute
10:50 1 Mar '07  
I've wrapped your groovy-cool Text Box into my application, but am going round-and-round in circles trying to get it to print and print preview.

Any suggestions would be greatly appreciated. I've got to give it up for today... my hair hurts.

Confused



Zute

AnswerRe: Print and Print Preview Contents of RTF
Declan Brennan
4:40 20 Mar '07  
Hi there,

I'll have a think about print preview and get back to you. In the meanwhile, could you give me a little more detail about what you've tried and the issues that you have had,

Thanks,

Dec.

Declan Brennan Chief Architect
Sekos Technology Ltd
www.sekos.com

GeneralRe: Print and Print Preview Contents of RTF
NaughtyZute
11:57 20 Mar '07  
I simply couldn't find a Print or PrintPreview method on this RichTextBox. What I did was "cobble" together two project to make it work. I tried to use thie application in C# which had been converted from VB: http://www.c-sharpcorner.com/UploadFile/scottlysle/WordProcessor02042007234628PM/WordProcessor.aspx but found that it wouldn't compile due to errors. Finally, I found the original code in VB and wrapped that dll into my C# project.

Sorry if this isn't the information you had in mind. I'm pretty new to C# and .NET in general and still trying to get comfortable with the syntax.

Thanks for your reply!


Zute

GeneralBinding as part of a master-detail type setup? [modified]
Jefffarr
9:28 20 Nov '06  
Ok, I'm still a bit confused about how to use this control properly. I've got a fairly simple program that uses a datagrid view to display a master list of trouble reports and I'd like to use this control for the users to type (or copy and paste) their trouble description into. I've not used the .databindings.add() method yet, so I'm not totally familiar with how to format the first argument.

I'm also not understanding exactly how adding the properties is allowing the RTB to be bound, and then how to properly bind it. Any clarification or other reading reguarding these procedures would be appreciated.

EDIT: Ok, I'm much more up to speed on what is going on now, but clearly I'm still missing an important peice of the puzzle. When I attempt to bind the RTB to a table in a dataset like so:

RTB.DataBindings.Add("Rtf", ds, "Table.Column", true);
This compiles just fine, but it doesn't seem to do anything, the RTB remains empty reguarless of the table/column used or user interaction

In order to get the control into my app I build the code and then added the .dll to my toolbox

Any hints?







-- modified at 17:38 Monday 20th November, 2006
QuestionPersisting Rich Text Fails when Databinding
ptemp
4:52 21 Sep '06  
Dear all,

I have created a control tha inherits from RichTextBox as follows (no need to place it in a user control panel)

MyRichTextBox : RichTextBox

and I want to bind its Rtf property.

The implementation is simple as that:

[BindableAttribute(true)]
public string RichText
{
get
{
m_RichText = Rtf;
return Rtf;
}
set
{
if (m_RichText != value)
{
m_RichText = value;
Rtf = value;
}
}
}


However, if the RichText property is binded in a row that is also binded in a DataGridView, a strange thing happens.
Lets say for instance that we have a table with two rows.
Row1: ID1, Title1, RtfText1
Row2 ID2, Title2, RtfText2 and lets say that the Grid Displays ID and Title. A MyRichTextBox is also placed on he same form, with its RichText property binded to field 'RtfText' of the table.
All fields have different values.

Now, after the databinding is complete, if you move from row 1 to row 2 oin the grid, the MyRichTextBox control shows the correct and different values each time.
However, if you sort the grid (by clicking on the header) thus changing the selected row, the contents for the MyRichTextBox are also set as the value of the other record.

Has anyone came across that?
What is the problem?

(Mind you that if you bind the defualt Text property if the MyRichTextBox with no extra code, everything works just fine!)
AnswerRe: Persisting Rich Text Fails when Databinding
Declan Brennan
1:46 22 Sep '06  
You need an RtfChanged event.

This is covered in "How to get the Rtf property to work" in the article,



Declan Brennan Chief Architect
Sekos Technology Ltd
www.sekos.com

GeneralHow to add a right click contenMenu to richTextControl?
gafferuk
14:15 28 Aug '06  
Anyone know how to add a right click content menu to the rich text control?
When I add one I can right click on tool bar but not the richTextControl.

GeneralStop paste images into control
gafferuk
8:57 28 Aug '06  
Any way to stop people pasting images in to richTextControl?
GeneralBuilding data from http server
gafferuk
8:12 27 Aug '06  
Im receiving data from a http server, how do i build up the data prior to applying it to the rich text control?

my code:
string totalResult;
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
string totalResult = "";
while ((result = sr.ReadLine()) != null)
{
totalResult += result + "\n";

}
richTextBoxExtended1.Rtf = totalResult.ToString();

}



how do I build the string because using "\n" as a line break is not working.
GeneralRe: Building data from http server
gafferuk
8:46 28 Aug '06  
Found my answer, it should be Environment.NewLine
GeneralHow to set rtf data?
gafferuk
4:08 27 Aug '06  
I have included 2 on my form and am using following code on a button:

richTextBoxExtended1.Rtf = richTextBoxExtended1.Rtf;

when I press my button the text is not copyed over. What am i missing? Thanks.
GeneralRe: How to set rtf data?
gafferuk
8:09 27 Aug '06  
Fixed it ,it should of been:

richTextBoxExtended1.Rtf = richTextBoxExtended1.Rtf.toString();
GeneralRTF datatype
cookie king
6:24 1 Aug '06  
I am new to dot net and I am struggling a little with this. I believe that it has something to do with my datatype. I am using and oracle database. I have tried to create a colume datatype CLOB but I receive an error message. Am I missing something? Should it be CLOB(1000) or a totally different datatype?
TIA

jaxkookie
QuestionCan we edit .MHTML content in rich text box control?
truongpham
1:22 31 Jul '06  
I found this article very useful. It's good to save data into RTF format.
But how about .MHTML format? Is it possible to convert this data into .MHTML format?
GeneralToolbar becomes invisible
bdSGIIMS
10:36 9 Jun '06  
I compiled the standalone component in Vs2005. It compiled OK. thena I added it to my toolbox and dragged it to my form on a page of a tab control. While working in the IDE and without touching anything to do with this control, I notice that without any apparent reason the toolbarvisible property changes to false and when using the control in the compiled prog, there's no toolbar. I think I fixed this unpredictable behaviour by putting Richtextboxextended1.toolbarvisible = true in the form load event.

Maybe someone knows why this would happen and clean up the problem a bit, otherwise the control is absolutely great! I bind it to a database field in sql server 2000, type text, so my users are not going to hit any practical limits as to length. It works like a charm.
Thanks a lot!


Robert Dufour
President
SGI-IMS Inc.
GeneralTrying to use but something is weird
bdSGIIMS
18:27 7 Jun '06  
1- I noticed that there were ome third party controls in the version I downloaded, so Iremoved the references and the code parts that did conditional compilation using these controls and recompiled control. Then added the recompiled control to my toolbox. Did this in vs2005. Oh, also localize the control by adding a tooltip and tooltip texts in english and french to the toolbar buttons.
2- I can drag the control over to my form in vs2005 and as i drag it over I see the control with its toolbar buttons OK on my form, but whats weird is that after that, as i develop my form further in the IDE, the control buttons seem to dissapear and only the overall outline of the control remains visible. When I run the app, the control does not show. I sould say that I'm using it in a vb.Net 2005 project but afaik that should not cause this behaviour. Any else had something similar? I would eventually like to use your control bound to a sql server 2000 text field and it looks like it should be able to do that just fine but I'm at a loss to understand why its behaving as it does. Any ideas or suggestions on how to fix this would be appreciated.

Robert Dufour
President
SGI-IMS Inc.
Generalwhy RtfChanged event - answer...
werdmuller
20:07 2 Jun '06  
Great article, very useful!

I didn't understand why there is a need for the RtfChanged event until I found the answer at the following link:
http://www.dotnet247.com/247reference/msgs/55/278244.aspx

The only way that the binding class can know when the property has changed is if it finds an event that matches the property name plus changed. If it doesn't find one, it will always assume it to be dirty and won't touch it.

Rtf is the binding propery, add changed and there you go we get RtfChanged. In case you want to bind the Text propery you would need to add an event called TextChanged and add an extra call to this event at the same places as where RtfChanged it called.
GeneralMinor Problem
Tailslide
11:35 22 Mar '06  

Hi this is a great control and has saved me a ton of work, thank you!
I'm using it with VS2005 and I have run into one small problem.

The databound value is not saved to the dataset until the user tabs out of the control. If you click the close button on a window and then try to save the record in the closing event the dataset does not have the value. Other databound controls do not behave this way and it create a bit of a problem.

You can't just copy over the values to your dataset because even if the values are identical I think this causes the row to be flagged as updated. Plus you need to check for null and so on. The result is that I'm using the databinding for reading but manually put the values back into the dataset with code.

I'm up against a deadline so I can't investigate further but I thought I'd mention it. Who knows, maybe the control is fine and I'm just doing something wrong.


Last Updated 3 Mar 2006 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010