Search code examples
c#richtextboxrtfrichtext

Decimal tab in rich text box


I have some content that will be displayed in a C# rich text box. I would like to have one of the columns displayed with the decimal points aligned:

//  Title                      Price
//  Item1                     1234.56
//  Item2                       78.90
//  Item3                        1.2

Below is code that was used in a (failed) attempt to build a string in memory before passing it to the RichTextBox control.

message = "";
message += @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033" +
           @"{\*\generator Msftedit 5.41.21.2509;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22 TEST RICH TEXT BOX \par";
message += @"\pard\sa200\sl276\slmult1\tx4000\ul\b Title\ulnone\b0\tab\ul\b Price\ulnone\b0\line\pard\sa200\sl276\slmult1\tx5000\tqdec\par ";
message += String.Format(@"{0}\tab {1} \line ", "Item1", 1234.56);
message += String.Format(@"{0}\tab {1} \line ", "Item2", 78.90);
message += String.Format(@"{0}\tab {1} \line ", "Item3", 1.2);
message += @"\par}";

using this the result looks like:

//  Title                      Price
//  Item1                     1234.56
//  Item2                     78.90
//  Item3                     1.2

I moved the \tqdec (decimal tab) command before the \tx5000 (tab 5000 twips from left edge) without success. Also attempted using the \tqr (tab align right) command without success.

Suggestions are appreciated


Solution

  • Wow, I'm not sure if your real intent is to modify RTF source text or if you are doing it only for the purpose of aligning your text. In the following, I am assuming that you are working with a normal string where tabs are escaped as \t and new lines as \r\n. (You should not need to edit the source RTF property to enter text under normal circumstances... I assume you have a good reason for doing so...)

    Does this code work? Do you mind the trailing 0's? By the way, tabs won't help you align text. You must use the string format options to insert spaces where you need them.

            message += String.Format("{0}\t {1,10:#####0.00} \r\n", "Item1", 1234.56);
            message += String.Format("{0}\t {1,10:#####0.00} \r\n", "Item2", 78.90);
            message += String.Format("{0}\t {1,10:#####0.00} \r\n", "Item3", 1.2);
    

    Output:

    Item1     1234.56 
    Item2       78.90 
    Item3        1.20 
    

    Another approach is to insert a table (I believe that RTF supports tables, right?), then pad your numbers with 0's at the right and finally right-align the column as Excel would do.