Problems with spacing in RichTextBox

OMRebel

Active member
Joined
Sep 27, 2006
Messages
44
Programming Experience
Beginner
Hey everyone, I've got a question. I have a form that has a RichTextBox on it. In that RTB, I populate it with a query. However, what I am wanting to do is make equal spacing between each field returned, so that everything lines up. I'm not real sure how to fix it.

I tried equaling out the spacing by using this code here:

VB.NET:
For Each rowCurrent In table1.Rows
            intCode = rowCurrent("Code")
            strCode = intCode.ToString
            intLength = strCode.Length
            useLength = 10 - intLength
            strCode.PadRight(10, " ")
            For counter = 1 To useLength
                strCode = strCode + " " 'trying to align
            Next
            intTemp = strCode.Length

            strCode = rowCurrent("Code")
            strDescription = rowCurrent("Description")
            rtbCharge.AppendText("     " + strCode + "   " + strDescription)
            rtbCharge.AppendText(Chr(13))
        Next
However, that doesn't work, so I'm not real sure what to do at this point. Anyone got any suggestions?

Here's the complete code from my form just in case:

VB.NET:
Imports System.Drawing.Printing
Imports System.Windows.Forms.Form


Public Class frmChargeListing

    Dim con As New OleDb.OleDbConnection
    Dim ds As New DataSet
    Dim da As OleDb.OleDbDataAdapter
    Dim sql As String
    Dim table1 As DataTable
    Dim counter As Integer
    Dim intCode As Integer
    Dim strDescription As String
    Dim rowCurrent As DataRow
    Dim strCode As String
    Dim intLength As Integer
    Dim useLength As Integer
    Dim intTemp As Integer


    Private Sub frmChargeListing_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = c:\ProFees\profees.mdb"
        con.Open()
        sql = "Select * from tblCharges"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "Charges")

        table1 = ds.Tables("Charges")
        rtbCharge.AppendText("                                 Charge Listing" + (Chr(13)))  ' Title
        For Each rowCurrent In table1.Rows
            intCode = rowCurrent("Code")
            strCode = intCode.ToString
            intLength = strCode.Length
            useLength = 10 - intLength
            strCode.PadRight(10, " ")
            For counter = 1 To useLength
                strCode = strCode + " " 'trying to align
            Next
            intTemp = strCode.Length

            strCode = rowCurrent("Code")
            strDescription = rowCurrent("Description")
            rtbCharge.AppendText("     " + strCode + "   " + strDescription)
            rtbCharge.AppendText(Chr(13))
        Next
    End Sub

    Private Sub PrintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintToolStripMenuItem.Click
        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            ' showDialog method makes the dialog box visible at run time
            PrintDocument1.Print()
        End If
    End Sub

    Private Sub PrintPreviewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintPreviewToolStripMenuItem.Click
        Try
            PrintPreviewDialog1.ShowDialog()
        Catch es As Exception
            MessageBox.Show(es.Message)
        End Try
    End Sub

    Private Sub PageSetupToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PageSetupToolStripMenuItem.Click
        With PageSetupDialog1
            .PageSettings = PrintDocument1.DefaultPageSettings
        End With
        Try
            If PageSetupDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                PrintDocument1.DefaultPageSettings = PageSetupDialog1.PageSettings
            End If
        Catch es As Exception
            MessageBox.Show(es.Message)
        End Try
    End Sub

    Private Sub PPControlToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PPControlToolStripMenuItem.Click
        Try
            PrintPreviewControl1.Document = PrintDocument1
        Catch es As Exception
            MessageBox.Show(es.Message)
        End Try
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        ' PrintPage is the foundational printing event.  This event gets fired for every
        ' page that will be printed
        Static intCurrentChar As Int32
        ' declaring a static variable to hold the position of the last printed char
        Dim font As New Font("Verdana", 14)
        ' initiating the font to be used for printing
        Dim PrintAreaHeight, PrintAreaWidth, marginLeft, marginTop As Int32
        With PrintDocument1.DefaultPageSettings
            ' initializing local variables that contain the bounds of the printing area rectangle
            PrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
            PrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
            ' initializing local variables to hold margin values that will serve
            ' as the X and Y coordinates for the upper left corner of the printing
            ' area rectangle.
            marginLeft = .Margins.Left
            marginTop = .Margins.Top
            ' X and Y coordinate
        End With

        If PrintDocument1.DefaultPageSettings.Landscape Then
            Dim intTemp As Int32
            intTemp = PrintAreaHeight
            PrintAreaHeight = PrintAreaWidth
            PrintAreaWidth = intTemp
            ' if the user selects landscape mode, swap the printing area height and width
        End If

        Dim intLineCount As Int32 = CInt(PrintAreaHeight / font.Height)
        ' calculating the total number of lines in the document based on the height of
        ' the printing area and the height of the font
        Dim rectPrintingArea As New RectangleF(marginLeft, marginTop, PrintAreaWidth, PrintAreaHeight)
        ' initializing the rectangle structure that defines the printing area
        Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
        ' instantiating the StringFormat class, which encapsulates text layout information
        Dim intLinesFilled, intCharsFitted As Int32

        '*******************************************************************************
        e.Graphics.MeasureString(Mid(rtbCharge.Text, intCurrentChar + 1), font, _
            New SizeF(PrintAreaWidth, PrintAreaHeight), fmt, intCharsFitted, intLinesFilled)
        '*******************************************************************************

        ' calling MeasureString to determine the number of characters that will fit in
        ' the printing area rectangle
        '*******************************************************************************
        e.Graphics.DrawString(Mid(rtbCharge.Text, intCurrentChar + 1), font, _
            Brushes.Black, rectPrintingArea, fmt)
        '*******************************************************************************
        ' print the text to the page
        intCurrentChar += intCharsFitted
        ' advancing the current char to the last char printed on this page

        '*******************************************************************************
        If intCurrentChar < rtbCharge.Text.Length Then
            '*******************************************************************************
            e.HasMorePages = True
        Else
            'HasMorePages tells the printing module whether another PrintPage event should be fired
            e.HasMorePages = False
            intCurrentChar = 0
        End If

    End Sub

    Private Sub FillByToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Me.TblChargesTableAdapter.FillBy(Me.ProfeesDataSet.tblCharges)
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub
End Class
 
Rich Textbox

Hey guys, quick question. I'm running a query that grabs some fields, and I'm populating that information into a rich textbox by using:
rtbTrans.AppendText(dDate + " " + strAccount + " " + strFirst + " " + strLast + " " + strCharge + " " + strPhys)

However, the spacing is off, because some of the strings are not always the same length. How can I correct this so that I can force it to be a certain length?
 
Either
- find longest string of each 'column' and add spaces to the other variable strings in same 'column' so each 'column' is equal length (for this to work you must also use a font that displays each character equal width, Courier New or Lucida Console for example)
Or
- implement RTF codes for table in the RichTextBox.RTF according to the RTF specification (download specs ver.1.8 from Microsoft see the 'Table Definitions' paragraph). There is no built in support for this in .Net RichTextBox or other .Net classes, you may be able to find custom classes/libraries on the web that have implemented this. To see example source code create a new document with a simple table in one of the 'proper' editors like Word or OpenOffice Writer and save it as RTF. Now you can look at the rtf codes by opening the document in Notepad, it will look very advanced with lots and lots of rtf codes. Load the same document into the RichTextBox control and display the .RTF property text, you should now see a much simplified outline of the rtf table source code.
 
Thanks for the input. I'll do some studying up on that and give it a go. I only had a quick 6 week course in VB, so there's alot that I still need to learn. Fortunatley, I've been able to write the entire application and get everything going (thanks to alot of help from this board). All I have to figure out now is the spacing. Again, thanks for the info.
 
That worked perfectly! For those that are learning like me, this is what I did:
strFirst = rowCurrent("FirstName")
intLength = strFirst.Length
useLength = 10 - intLength
For counter = 1 To useLength
strFirst = strFirst + " "
Next

I changed the font to Courier New, and counted the length for each column that isn't a set length, and everything looks good.

Thanks everyone!
 
There also one little helper method in String.Format , see the remarks in that page for more explanation. In the formatting string the indexed items can be left/right aligned to specified lengths. You still have to find longest string in column to be used when setting up the string format, and you still have to use a font that write each character equal length. Example, using the StringBuilder and .AppendFormat method here, it is most correct for lots of string concenation, but behaves same as String.Format:
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] fmt [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"{0,7} {1,-10} {2,10}{3}"[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] txt1 [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"123456"[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] txt2 [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"12345"[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] txt3 [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"1234"[/COLOR][/SIZE]
[SIZE=2][SIZE=2][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] sb [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] System.Text.StringBuilder[/SIZE]
sb.AppendFormat(fmt, [/SIZE][SIZE=2][COLOR=#800000]"header1"[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#800000]"header2"[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#800000]"header3"[/COLOR][/SIZE][SIZE=2], vbNewLine)[/SIZE]
[SIZE=2]sb.AppendFormat(fmt, txt1, txt3, txt2, vbNewLine)[/SIZE]
[SIZE=2]sb.AppendFormat(fmt, txt2, txt1, txt3, vbNewLine)[/SIZE]
[SIZE=2]sb.AppendFormat(fmt, txt3, txt2, txt1, vbNewLine)[/SIZE]
[SIZE=2]RichTextBox1.Text = sb.ToString[/SIZE]
[/SIZE]
 
Back
Top