Click here to Skip to main content
6,306,412 members and growing! (20,763 online)
Email Password   helpLost your password?
Languages » VB.NET » General     Intermediate

Line Numbering of RichTextBox in .NET 2.0

By Michael Elly

Line numbering of a RichTextBox control using PictureBox control painting
VB, Windows, .NET, Visual Studio, Dev
Posted:25 Jun 2006
Updated:26 Jan 2007
Views:48,730
Bookmarked:43 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
10 votes for this article.
Popularity: 3.79 Rating: 3.79 out of 5

1
1 vote, 10.0%
2
3 votes, 30.0%
3
1 vote, 10.0%
4
5 votes, 50.0%
5
Sample Image - sample.jpg

Introduction

This article demonstrates how to add line numbers to a rich text box control. This is done by adding a picture box control on the left side of the rich text box control. When the appropriate events happen on the Form or on the RichTextBox control we call a method that paints the line numbers on the PictureBox control. This approach is more accurate and efficient than other approaches I've seen where another textbox control was used for printing the line numbers. The PictureBox will only print the line numbers that are currently visible in the RichTextBox control.
During the process of constructing this code sample, I initially based it on the code sample provided in the article http://www.codeproject.com/cs/miscctrl/numberedtextbox.asp and enhanced it by doing the following:
  1. Replace the Label control for numbering with a PictureBox
  2. I fixed the scrolling problem with that implementation due to the fact that RichTextBox uses smooth scrolling (scrolling with the scrollbar scrolls the text in pixels, not in lines), as a result sometimes the first line may be displayed in half, at which case the line numbering should address it.
Here is the code for printing the line numbers. Note that we have a RichTextBox control
called MyRichTextBox and a PictureBox control called MyPictureBox. The method gets one
argument which is the Graphics of the PictureBox control.
This is the method DrawRichTextBoxLineNumbers:
 Private Sub DrawRichTextBoxLineNumbers(ByRef g As Graphics)
  'Calculate font heigth as the difference in Y coordinate 
  'between line 2 and line 1
  'Note that the RichTextBox text must have at least two lines. 
  '  So the initial Text property of the RichTextBox 
  '  should not be an empty string. It could be something 
  '  like vbcrlf & vbcrlf & vbcrlf 
  With MyRichTextBox
   Dim font_height As Single 
   font_height = .GetPositionFromCharIndex(.GetFirstCharIndexFromLine(2)).Y _
         - .GetPositionFromCharIndex(.GetFirstCharIndexFromLine(1)).Y
   If font_height = 0 Then Exit Sub

   'Get the first line index and location
   Dim first_index As Integer
   Dim first_line As Integer
   Dim first_line_y As Integer
   first_index = .GetCharIndexFromPosition(New _
         Point(0, g.VisibleClipBounds.Y + font_height / 3))
   first_line = .GetLineFromCharIndex(first_index)
   first_line_y = .GetPositionFromCharIndex(first_index).Y

   'Print on the PictureBox the visible line numbers of the RichTextBox
   g.Clear(Control.DefaultBackColor)
   Dim i As Integer = first_line
   Dim y As Single
   Do While y < g.VisibleClipBounds.Y + g.VisibleClipBounds.Height
    y = first_line_y + 2 + font_height * (i - first_line - 1)
    g.DrawString((i).ToString, .Font, Brushes.DarkBlue, MyPictureBox.Width _
          - g.MeasureString((i).ToString, .Font).Width, y)
    i += 1
   Loop
   'Debug.WriteLine("Finished: " & firstLine + 1 & " " & i - 1)
  End With
 End Sub

This method should be called from the following locations:

  1. Upon RichTextBox Resize event. DrawRichTextBoxLineNumbers(MyPictureBox.CreateGraphics)
  2. When VScroll event happens on the RichTextBox (MyRichTextBox.VScroll). DrawRichTextBoxLineNumbers(MyPictureBox.CreateGraphics)
  3. When Paint Event happens (MyPictureBox.Paint). DrawRichTextBoxLineNumbers(e.Graphics). Note that at this method we send e.Graphics and not MyPictureBox.CreateGraphics as we would like to repaint only the required region whithin the PictureBox control. 

These are the locations from which we need to invoke the line numbering method:
 Private Sub r_Resize(ByVal sender As Object, ByVal e As System.EventArgs) _
     Handles MyRichTextBox.Resize
MyPictureBox.Invalidate() End Sub Private Sub r_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles MyRichTextBox.VScroll MyPictureBox.Invalidate() End Sub Private Sub p_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) _ Handles MyPictureBox.Paint DrawRichTextBoxLineNumbers(e.Graphics) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load MyRichTextBox.Text = vbCrLf & vbCrLf & vbCrLf End Sub

Other general notes

  1. The code above assumes that the font name and size of the RichTextBox control is the same for the entire text.
  2. The WordWrap property of the RichTextBox control should be set to false.
  3. I've placed this code in the Form_Load method to assure that the textbox has at least two lines always. MyRichTextBox.Text = vbCrLf & vbCrLf & vbCrLf
  4. I Recommend docking the PictureBox to the left and then calculating the width of the PictureBox based on g.MeasureString("000", MyRichTextBox.Font).Width. The width of the PictureBox should be recalculated and the PictureBox should be redrawn when the font of the RichTextBox changes.
  5. The PictureBox control may be replaced with a Panel or any other control that exposes the CreateGraphics() method.
  6. The control was designed for RichTextBox controls with WordWrap = False 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Michael Elly


Member

Location: United States United States

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
QuestionHi PinmemberBotsbushman14:09 11 Aug '08  
GeneralThanks PinmemberMember 44967309:51 6 May '08  
GeneralProblem with moving thumb PinmemberDipendu Paul2:18 5 Jul '07  
GeneralSimple code modifications PinmemberJason Barrera12:55 22 Jun '07  
QuestionText Change in coordinate with font changes... Pinmemberbrottmayer4:10 22 Feb '07  
GeneralLine numbering in C# - complete [modified] Pinmemberbiopsy6:44 15 Feb '07  
GeneralLooks great PinmemberAlexandru Lungu11:08 30 Jan '07  
GeneralHi PinmemberAhmed El-Badry2:47 25 Jan '07  
GeneralVb.net syntax Line Numbering of RichTextBox convertion to c# syntax PinmemberSirDre13:37 3 Jan '07  
GeneralResource leak due to CreateGraphics Pinmembermav.northwind23:01 25 Dec '06  
GeneralRe: Resource leak due to CreateGraphics PinmemberMichael Elly1:27 26 Jan '07  
GeneralAny way to make the code show line numbers only upto contained lines in the RTBox? Pinmemberkil0byte^bandit5:37 5 Dec '06  
GeneralRe: Any way to make the code show line numbers only upto contained lines in the RTBox? PinmemberMichael Elly21:19 6 Dec '06  
GeneralRe: Any way to make the code show line numbers only upto contained lines in the RTBox? Pinmembergabegabe5:20 4 Jan '07  
GeneralRe: Any way to make the code show line numbers only upto contained lines in the RTBox? PinmemberMichael Elly1:43 26 Jan '07  
Generalwordwrap linecount fix Pinmembergabegabe22:29 17 Jan '07  
General[Message Deleted] PinmemberArkady Lesniara5:24 26 Jun '06  
GeneralRe: Compile Problem PinmemberGuardianStorm7:27 26 Jun '06  
GeneralRe: Compile Problem Pinmembermicmelly7:43 27 Jun '06  
GeneralRe: Compile Problem PinmemberArkady Lesniara7:54 27 Jun '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Jan 2007
Editor:
Copyright 2006 by Michael Elly
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project