Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to transfer data from richtextbox to another richtextbox WPF C#

Tags:

c#

wpf

hi i have a problem in displaying or transfering the data in my richtextbox to other richtextbox...

richtextbox1.Document = richtextbox2.Document; //This will be the idea..

actually what i'm planning to do is, i want to transfer my data from my database to my listview which will display as what it is

SQLDataEHRemarks = myData["remarks"].ToString();// Here is my field from my database which is set as Memo
RichTextBox NewRichtextBox = new RichTextBox();// Now i created a new Richtextbox for me to take the data from SQLDataEHRemarks...
NewRichtextBox.Document.Blocks.Clear();// Clearing
TextRange tr2 = new TextRange(NewRichtextBox.Document.ContentStart, NewRichtextBox.Document.ContentEnd);// I found this code from other forum and helps me a lot by loading data from the database....
MemoryStream ms2 = GetMemoryStreamFromString(SQLDataEHRemarks);//This will Convert to String
tr2.Load(ms2, DataFormats.Rtf);//then Load the Data to my NewRichtextbox

Now what i want to do is, im going to load this data to my ListView.. or other control like textblock or textbox...

_EmpHistoryDataCollection.Add(new EmployeeHistoryObject{
EHTrackNum = tr2.ToString()  // The problem here is it will display only the first line of the paragraph.. not the whole paragraph
}); 
like image 293
Kenshi Hemura Avatar asked Oct 06 '22 10:10

Kenshi Hemura


1 Answers

Use the Text property of the TextRange instead of .ToString()

Method to get the content of a RichTextBox as string:

public static string GetStringFromRichTextBox(RichTextBox richTextBox)
{
    TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
    return textRange.Text;
}

Method to get the content of a RichTextBox as rich text:

public static string GetRtfStringFromRichTextBox(RichTextBox richTextBox)
{
    TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
    MemoryStream ms = new MemoryStream();
    textRange.Save(ms, DataFormats.Rtf);

    return Encoding.Default.GetString(ms.ToArray());
}

Edit: You can put the rich text returned from GetRtfStringFromRichTextBox() in another RichText control by doing the following:

FlowDocument fd = new FlowDocument();
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(richTextString));
TextRange textRange = new TextRange(fd.ContentStart, fd.ContentEnd);
textRange.Load(ms, DataFormats.Rtf);
richTextBox.Document = fd;
like image 141
Eirik Avatar answered Oct 10 '22 03:10

Eirik