DigitalJedi805
DigitalJedi805

Reputation: 1460

Inexplicable IndexOutOfRangeException

I've got a rich text box with multiple lines of text in it, and upon 'clicking' on a portion of the text, I'd like to extrapolate the line of text that has been clicked on, and write it out to another window for more processing - The issue I'm having is that in some circumstances the following code is throwing an IndexOutOfRangeException, which I would assess as impossible from my meager viewpoint... I would assume that there would be interopability between GetLineFromCharIndex() and RichTextBox.Lines; especially when using other 'inclusive' variables like the 'SelectionStart'.

In at least one circumstance, clicking on my 'last line' of text when there is an empty line following it ( making it not actually the last line... ) throws an exception.

    void OutputField_SelectionChanged(object sender, EventArgs e)
    {
        try
        {
            if (!this.LineEditor.Visible)
                this.LineEditor.Show();

            if (this.OutputField.SelectionStart == this.OutputField.TextLength)
                return;

            int TargetLine = this.OutputField.GetLineFromCharIndex(this.OutputField.SelectionStart);
            String LineText = this.OutputField.Lines[TargetLine];

            this.LineEditor.SetContent(TimeSpan.Zero, TimeSpan.Zero, LineText);

            return;
        }
        catch (Exception ex)
        {
        }
    }

Specifically; the line that I am finding exceptions on is the following;

String LineText = this.OutputField.Lines[TargetLine];

Any hints tips or suggestions would be much appreciated. Thanks folks.

Upvotes: 0

Views: 158

Answers (1)

TheEvilPenguin
TheEvilPenguin

Reputation: 5682

It looks like GetLineFromCharIndex() returns the actual line displayed on the screen, not necessarily the index from Lines[] if WordWrap is on. Give it a go with WordWrap off and see if it works as expected.

Reference

Upvotes: 1

Related Questions