Wednesday, March 26, 2008

Showing current line number of a TextBox (Windows Forms)

You need code like:

label.Text = string.Format("Line {0} Col {1}",
txt.GetLineFromCharIndex(txt.SelectionStart) + 1,
txt.SelectionStart - txt.GetFirstCharIndexOfCurrentLine() + 1);

But the above needs some adjustment because it doesn't work correctly when the user selects multiple lines (eg the column may be negative).

You need to update the line/column number upon these events:
  • Click
  • KeyDown
  • KeyUp
  • KeyPress (maybe? not sure)
  • TextChanged
No event is fired if the cursor position changes programmatically.

When the user presses arrows or Home/End/PgUp/PgDn, KeyDown is fired before the cursor position actually changes, so you trap it only to show the line number changing when the user holds down a key. KeyUp is fired after the cursor position changes to you can show the correct value.

You might want to show line numbers beside the text box, e.g. using a series of labels on the left side of the TextBox. This is not possible, at least not using pure Windows Forms code, because TextBox does not generate any events (not even click events) when it is scrolled via its scrollbars.