简体   繁体   中英

Multiline textbox number of lines does not match

I am working on a WinForms app, targeting .Net 4.5.2 and ran into the problem trying to get the line index of the current caret position from a multiline textbox.

It only works well using the GetLineFromCharIndex() method when all strings in the Lines property are short enough to fit the width of the textbox. However, when one of the strings is longer, it gets split into two lines. This is reflected in the index returned from GetLineFromCharIndex() , but not in the actual Lines property. The index is then off by one, causing an IndexOutOfRange exception when I try to use it to access the desired string from Lines .

When a string is so long that it spans over three lines, the index is off by two and so on.

private void monitor_TextBox_KeyDown(object sender, KeyEventArgs e)
{
    TextBox rtb = (TextBox)sender;
    int lineIndex = rtb.GetLineFromCharIndex(rtb.SelectionStart);
    string[] lines = rtb.Lines;

    if(e.KeyCode == Keys.Up)
    {
        e.SuppressKeyPress = true;
        string line = lines[lineIndex];  // exception occurs here
        ...
    }
}

Is there an event that is raised when a string is split into multiple lines or something like that?

I think the problem here is that the TextBox.Lines property thinks of a line as a string terminated with a '\\n'. So it will only return it as a new line if it got that new line symbole (you pressed enter).

What happens when the string is bigger then the TextBoxes width is WordWrapping, it automaticaly renders the Text into a new line but does not add a '\\n'.

What you could do now is:

  1. Get the contents of the TextBox in a string.

  2. Loop thru every char of the TextBox and add it to a seperate String and if you exceeded the TextBoxes width add that to a list and clear that string. Also you need to check if there is a '\\n' then also add the String to the list and clear it !

  3. There you go, you got your own lines function that does not ignore WordWrapping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM