问题
This is my first time posting question on this amazing service, since today it has helped me a lot by just reading it.
Currently, I'm making small C# application where I need to use a lot of TextBoxes. In TextBox Properties I have checked MultiLine and Word-Wrap functions. So when user enters text, it is displayed correctly in multiple lines.
My problem is how can I get those lines, which are displayed on form, in list of strings, instead of one big string.
I haven yet distinguished weather Word-Wrap Function makes new lines or adds "\n\r" at the end of every line. I tried to get lines from TextBox.Lines , but it has only TextBox.Lines[0], which contains the whole string form TextBox
I have already tried many things and researched many resources, but I still haven't found right solution for this problem.
回答1:
Lots of corner cases here. The core method you want use is TextBox.GetFirstCharIndexFromLine()
, that lets you iterate the lines after TextBox has applied the WordWrap property. Boilerplate 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 line-endings are included in lines.
回答2:
It is possible to get the line count and build an array of lines directly. This is inclusive of lines generated 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:
You can pull out the single string
and then do whatever you want with it.
Splitting a string into a list of strings based on a separator is straightforward:
https://stackoverflow.com/a/1814568/13895
来源:https://stackoverflow.com/questions/12682209/textbox-word-wrapping-splitting-string-to-lines