Click to See Complete Forum and Search --> : Problem with RichTextBox


underwar
February 24th, 2003, 05:23 PM
I'm writing a text editor using RTB (RichTextBox), and I would like to display the line and the offset of the caret on the status bar.
I can grab the line number using
RTB.GetLineFromCharIndex(RTB.SelectedIndex);
but I can't find how to find the offset in the line.

Any has a solution?

pareshgh
February 24th, 2003, 05:42 PM
check out this code

private void GoToLineAndColumn(RichTextBox RTB, int Line, int Column)

{

int offset = 0;

for (int i = 0; i < Line - 1 && i < RTB.Lines.Length; i++)

{

offset += RTB.Lines[i].Length + 1;

}

RTB.Focus();

RTB.Select(offset + Column, 0);

}



Paresh

underwar
February 24th, 2003, 06:14 PM
Looks good. Thanks.

Here's my final solution, in case anyone in the future will need it.
At the end of the following code, iLine contains the caret's line number and iCol contains the column.

int iLine = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) + 1;
int iOffset = 0;
for (int i = 0; i < iLine - 1; ++i)
{
iOffset += richTextBox1.Lines[i].Length + 1;
}
int iCol = richTextBox1.SelectionStart - iOffset;

pareshgh
February 24th, 2003, 06:17 PM
yes, that looks nice and neat code.
may be it can be used somewhere...

good work kep it up:D

Crash1hd
March 2nd, 2005, 01:50 AM
WOW Thankyou I have been trying to figure out how to do this for three days lol :) I finally realized how to spell caret lol and boom here it is thankyou thankyou thankyou p.s. I slightly changed the code as I wanted to mimic notepad and the col was off by 1 so your code said that the col is 0 when it actually is 1 below is my code :)

P.S. Thankyou again :)

int iLine = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) + 1;
int iOffset = 0;
for (int i = 0; i < iLine - 1; ++i)
{
iOffset += richTextBox1.Lines[i].Length + 1;
}
int iCol = (richTextBox1.SelectionStart - iOffset) + 1;
this.statusBarPanel2.Text = "Ln " + iLine + ", Col " + iCol;

oh did I say thankyou :)

I found this link but it was way to much code and yes this code is nice and neat :)

http://www.codeguru.com/Csharp/Csharp/cs_controls/custom/print.php/c8145/

and my link to my post on this site was here :)

http://www.codeguru.com/forum/showthread.php?p=1105669#post1105669

Thankyou again

I do have one small problem I put it into the _MouseDown and the _KeyPress works great except when I use the arrow keys and the delete key ext... is there one spot that I can put it where it will work whether or not its a mouse click or a key pressed (All keys relevent including arrow keys ext...)

Help