Categories: C#

How To Create Table in RichTextbox Using C#

This article is to guide C#  and VB.NET developers in creating a table in RichTextBox using C# and in a similar manner in VB.NET.

Being a .NET programmer, you may have to edit formatted text, images, tables and any other such rich content. With simple textbox control, it is not possible. Here comes the use of Rich Text Box control.

Rich Text Format (RTF) specifications enable to format text and graphics. This formatting feature helps Rich Text Format to be used with different output devices, different operating systems, and operating environments.

RTF documents created with different software applications under different operating systems can be transferred between those software applications and operating systems. For a detailed understanding of Rich Text Format read Rich Text Format  Specification.The RichTextBox control permits the user to enter and edit text with more advanced formatting features than the simple textbox control.

Is it possible To Create Table in RichTextBox?

Now coming to the use of RichTextBox control, common questions are Is it possible to make Table in RichTextBox? and How to create Table in RichTextBox? So in this post, we will try to clear your doubt. After reading this article you will get a clear understanding of how to insert Tables in RichTextBox control using C#.

Yes, It is possible to make a table appear in a RichTextBox with a little effort. Though, columns and rows cannot be interactively resized or modified too much we can have table in RichTextBox controls.

Table in RichTextBox Using C#

We will be covering few C# examples here to make table appear in RichTextBox. Same thing can be followed in VB.NET also.

For better understanding check the small sample given below. This example shows how to create a table with 5 rows and 3 columns in RichTextbox control. You can extend the number of rows and columns as per your need.

In this example, we will be using a StringBuilder object for creating rows,cells, and manipulating characters.Unlike simple string, StringBuilder normally contains a buffer, which can be manipulated(insert, append, remove, and replace) in place without creating another new string.
After we completely set the table string format, set this StringBuilder object to RichTextBox control.
Here below you can see 2 examples. In the first example, we will create rows and cells one by one. The second one will create the table in a loop by accepting parameters passed through the method call. No of rows, columns and width of cell are passed as parameters.You can choose whichever is most suitable for you.

Create Table in RichTextBox – Example 1

I Created a new Winform Project. In Form, dragged and dropped a RichTextBox Control and named it as richTextBox1(Set the rich text box width accordingly to accommodate the table completely).
Added one button below the RichTextBox control and name it as btnCreateTable.

See the code snippet below,

// Method to create a table format string which can directly be set to 
// RichTextBox Control
private void InsertTableInRichtextbox()
{
    //CreateStringBuilder object
    StringBuilder strTable = new StringBuilder();

    //Beginning of rich text format,don’t alter this line
    strTable.Append(@"{\rtf1 ");
   
    //Create 5 rows with 4 columns
    for(inti = 0; i< 5; i++)
    {
       //Start the row
       strTable.Append(@"\trowd");

       //First cell with width 1000.
       strTable.Append(@"\cellx1000");

       //Second cell with width 1000.Ending point is 2000, which is 1000+1000.
       strTable.Append(@"\cellx2000");

       //Third cell with width 1000.Endingat3000,which is 2000+1000.
       strTable.Append(@"\cellx3000");

       //Last cell with width 1000.Ending at 4000 (which is 3000+1000)
       sringTableRtf.Append(@"\cellx4000");

       //Append the row in StringBuilder
       strTable.Append(@"\intbl \cell \row"); //create the row
    }

    strTable.Append(@"\pard");

    strTable.Append(@"}");

     this.richTextBox1.Rtf = strTable.ToString();
}

Click of the button will create the table. In button click event Invoke the InsertTableInRichTextBox function and assign the return string to the RichTextBox control. Update button click event as below.

private void btnCreateTable_Click(object sender, EventArgs e) 
{ 
    /*Insert Table in RichTextBox Control by setting .Rtf as the string returned. 
     Set the RichTextBox width to fit the table completely. */    this.richTextBox.Rtf = InsertTableInRichTextBox();
}

The above code will create a table with 5 rows and 3 columns in the rich text box control.

Create Table in RichTextBox – Example 2

In the same Form above change the functions as below,

/* Method to create a table format string which can directly be set to 
   RichTextBoxControl. Rows, columns and cell width are passed as parameters 
   rather than hard coding as in previous example.*/private static String InsertTableInRichTextBox(int rows, int cols, int width)
{
    //Create StringBuilder Instance
    StringBuilder sringTableRtf = new StringBuilder();

    //beginning of rich text format
    sringTableRtf.Append(@"{\rtf1 ");

    //Variable for cell width
    int cellWidth;

    //Start row
    sringTableRtf.Append(@"\trowd");

    //Loop to create table string
    for (inti = 0; i< rows; i++)
    {
       sringTableRtf.Append(@"\trowd");

       for (int j = 0; j < cols; j++)
       {
           //Calculate cell end point for each cell
           cellWidth = (j + 1) * width;

           //A cell with width 1000 in each iteration.
          sringTableRtf.Append(@"\cellx" + cellWidth.ToString());
       }

       //Append the row in StringBuilder
       sringTableRtf.Append(@"\intbl \cell \row");
    }
    sringTableRtf.Append(@"\pard");
    sringTableRtf.Append(@"}");

    return sringTableRtf.ToString();
}

On click of button,table will be created. Invoke the InsertTableInRichTextBox function with required parameter values forrows, columns and cell width

private void btnCreateTable_Click(object sender, EventArgs e)
{
    //Insert Table in RichTextBox Control by setting .Rtf as the string returned.
    //Set the RichTextBox width to fit the table completely,
    this.richTextBox.Rtf = InsertTableInRichTextBox(5,4,1000);
}

Both the examples will create table in rich text as,

In the above-mentioned sample of table creation in rich textbox control, we cannot enter long texts in cells, which seems a limitation of the .NET RichTexBox control. So, I have written another article to overcome this limitation which will allow auto text wrap in table columns. See the article here Table in RichTextBox With Text Wrap In Columns.

Summary

Don’t forget to provide you thoughts and suggestions in the comments section below. If you know any better approach than this for creating a table in rich textbox control in C#, please share it here.

Rajeev

View Comments

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

1 year ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

1 year ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

1 year ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

1 year ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

1 year ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

1 year ago