简体   繁体   中英

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

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
}); 

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;

不会将 RichTextBox 的内容作为字符串获取,只是类似于以下内容(在 VB.Net 中)

Dim strText as string = MyRTB.text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM