Friday, October 30, 2009

How to save/load a TRichEdit to/from a string/stream

Recently I had to save a TRichEdit as a string so I can save it in a database field, after 1-2 hours I came up with this solutions
// this function extracts formatted string from a
// TRichEdit/TDBRichEdit or descendant and returns it as a TStream
function RichEditToStream(thisRichEdit: TRichEdit): TStream;
var ss : TStringStream;
begin
     ss := TStringStream.Create(EmptyStr);
     thisRichEdit.Lines.SaveToStream(ss);
     Result := ss;
     // you might need to set position to zero
     Result.Position := 0;
     // REMEMBER to free the stream variable
end;

// this functions returns the formatted of a
// TRichEdit/TDBRichEdit or descendant as plain string
function RichEditToString(thisRichEdit: TRichEdit): string;
var ss : TStringStream;
begin
     ss := TStringStream(RichEditToStream(thisRichEdit));
     Result := ss.DataString;
     FreeAndNil(ss);
end;

// this procedure loads formatted string from a
// string and loads it into a TRichEdit/TDBRichEdit or
// descendant
procedure RichEditFromStream(thisRichEdit: TRichEdit;
          const theString: string);
var ss : TStringStream;
begin
     ss := TStringStream.Create(theString);
     thisRichEdit.Lines.LoadFromStream(ss);
     FreeAndNil(ss);
end;

2 comments:

  1. Thanks, RichEditFromStream works great. I didn't try the other ones.

    ReplyDelete

Blogroll(General programming and Delphi feeds)