If you try to load an RTF file having a table with long text and display it in a normal RichTextBox control, you will get disappointed for sure. Because the basic out of the box RichTextBox doesn’t support word wrapping by default.
For example, you have an RTF file “rtfTest.rtf“ with a content table like this
Now if you use the RichTextBox control from .NET and load the rtf file in this control
//Load the rtf file from your location like below.
richTextBox.LoadFile("D:\\rtfTest.rtf");
You will get the output as below. The table structure even changed to accommodate the long string content.
This is not the one you expected. Because there seems limitation in the RichTextBox control.
Now the Solution is to create a custom control out of this RichTextBox control as below and load the file in that control instead .Follow the code described below.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace RichTextBoxRTFSample
{
class ExtendedRichTextBox : RichTextBox
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string dllName);
protected override CreateParams CreateParams
{
get
{
CreateParams baseParams = base.CreateParams;
if (LoadLibrary("msftedit.dll") != IntPtr.Zero)
{
baseParams.ClassName = "RICHEDIT50W";
}
return baseParams;
}
}
}
}
Load the rtf file in the above custom control.Use the below code snippet for loading and displaying the rtf file data.
//Instance of the customized control class
ExtendedRichTextBox richTextBox = new ExtendedRichTextBox();
//Set the initial size of the Rich TextBox
richTextBox.Size = new Size(500, 400);
this.Controls.Add(richTextBox);
//Bring the control to top level
richTextBox.BringToFront();
//Load the rtf file from your location like below.
richTextBox.LoadFile("D:\\rtfTest.rtf");
Run the application and see the output,
Summary:
This post and the previous post Table in RichTextBox With Text Wrap In Columns are addressing the issue of richtextbox while displaying RTF File With Table and long content In it. I hope,after reading this post you may not say again that RichTextBox control cannot display a .rtf file correctly. Share your thoughts below and share the post.
Happy Coding!
[…] Summary: This article will definitely help you in handling data in RichTextBox table.Provide your valuable suggestions and feedbacks in the comments below. Also you may be interested in article, Load and Display RTF file With Table InRichTextBox control […]