.NET Zone is brought to you in partnership with:

Robert is a South African technology specialist with focus on Microsoft technologies. He is very passionate about teaching and sharing and is a Microsoft MVP & Ranger. Robert is a DZone MVB and is not an employee of DZone and has posted 75 posts at DZone. You can read more from them at their website. View Full User Profile

Dealing With Off by x Issues When Using the TextBox

01.21.2013
| 1731 views |
  • submit to reddit
Introduction

One of the toughest problems I faced when I built Notepad Classic was an issue where many functions like Go To & Find were always off a few characters. After a bit of experimenting I noticed a pattern, it was off by the number of characters equal to the line number (0 based).

i.e.: no issues on the first line (line index 0); Off by one on the second line (line index 1); Off by two on the third line (line index 2); Off by three on the forth line etc…

Problem

It turned out that the way the string functions count a line break (i.e. \r\n) as two characters, and rightly so – it is two characters a \r & a \n. However the TextBox functions like Select treat \r\n as a single character because that is what is displayed visually – a line break is one character visually. So there is a difference between the two scenarios and thus the “off by one x line count” error I found.

Solution

The solution I used is to compensate for it by working out the number of lines to the point (i.e. count all the line breaks before the point) and adjusting the results (adding +1 for each \r\n) as needed.

Sample application to show this problem and the solution can be found at: https://bitbucket.org/rmaclean/off-by-one-line-sample-code/src

Published at DZone with permission of Robert Maclean, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)