TextBox Word-Wrapping splits a string into strings

This is my first question about this amazing service, because today it really helped me just by reading it.

I am currently making a small C # application where I need to use many text fields. In the TextBox properties, I checked the MultiLine and Word-Wrap functions. Therefore, when a user enters text, it is displayed correctly in several lines.

My problem is how can I get these lines that appear on the form in the list of lines instead of one big line.

I have not yet highlighted the Word-Wrap weather function by creating new lines or adding "\ n \ r" at the end of each line. I tried to get strings from TextBox.Lines , but it only has TextBox.Lines [0] which contains the entire string form of the TextBox

I have already tried and researched a lot of resources, but I still have not found the right solution to this problem.

+4
source share
3 answers

There are many corner cases. The main method you want to use is TextBox.GetFirstCharIndexFromLine() , which allows you to TextBox.GetFirstCharIndexFromLine() over the lines after the TextBox has applied the WordWrap property. Boiler code:

  var lines = new List<string>(); for (int line = 0; ;line++) { var start = textBox1.GetFirstCharIndexFromLine(line); if (start < 0) break; var end = textBox1.GetFirstCharIndexFromLine(line + 1); if (end == -1 || start == end) end = textBox1.Text.Length; lines.Add(textBox1.Text.Substring(start, end - start)); } // Do something with lines //... 

Beware that row strings are included in rows.

+6
source

You can get a row counter and build an array of strings directly. This includes strings created due to WordWrap.

 // Get the line count then loop and populate array int lineCount = textBox1.GetLineFromCharIndex(textBox1.Text.Length) + 1; // Build array of lines string[] lines = new string[lineCount]; for (int i = 0; i < lineCount; i++) { int start = textBox1.GetFirstCharIndexFromLine(i); int end = i < lineCount - 1 ? textBox1.GetFirstCharIndexFromLine(i + 1) : textBox1.Text.Length; lines[i] = textBox1.Text.Substring(start, end - start); } 
+3
source

You can pull out a single string and then do whatever you want with it.

Splitting a string into a list of strings based on a separator is simple:

fooobar.com/questions/109271 / ...

0
source

Source: https://habr.com/ru/post/1437301/


All Articles