Karl_Schuhmann
Karl_Schuhmann

Reputation: 1332

save the color of a text in a database and copy text with color into a richtextbox

I want to maintain the format of a text when i copy it into a richtextbox, How can i do this? (When you copy code in a microsoft word document, the color of the code will be the same as in Visual studio (show here http://img4.fotos-hochladen.net/uploads/unbenannta2k46fcjn5.png ))

And i want to save the text in a sql database and reload it with the same format(colors, etc.). I know how to save and read data in a database but how can i save the text with the format(color)?

Upvotes: 1

Views: 1825

Answers (2)

Arun
Arun

Reputation: 978

Use the Rtf property of the RichTextBox

richtextbox1.Rtf => Store to database

Retrieve from database and restore value in richtextbox1.Rtf.

Upvotes: -1

WiiMaxx
WiiMaxx

Reputation: 5420

you could also save the FlowDocument which is hiden in RichTextBox.Document as string

public static string ToStringExt(this IDocumentPaginatorSource flowDocument)
{
    return XamlWriter.Save(flowDocument);
}

to convert it back as FlowDocument you can use this extensions

public static bool IsFlowDocument(this string xamlString)
{
    if (xamlString.IsNullOrEmpty()) 
        throw new ArgumentNullException();

    if (xamlString.StartsWith("<") && xamlString.EndsWith(">"))
    {
        XmlDocument xml = new XmlDocument();
        try
        {
            xml.LoadXml(string.Format("<Root>{0}</Root>", xamlString));
            return true;
        }
        catch (XmlException)
        {
            return false;
        }
    }
    return false;
}

public static FlowDocument toFlowDocument(this string xamlString)
{
    if (IsFlowDocument(xamlString))
    {
        var stringReader = new StringReader(xamlString);
        var xmlReader = System.Xml.XmlReader.Create(stringReader);

        return XamlReader.Load(xmlReader) as FlowDocument;
    }
    else
    {
        Paragraph myParagraph = new Paragraph();
        myParagraph.Inlines.Add(new Run(xamlString));
        FlowDocument myFlowDocument = new FlowDocument();
        myFlowDocument.Blocks.Add(myParagraph);

        return myFlowDocument;
    }
}

Upvotes: 2

Related Questions