问题
I'm looking for the best way to sort lines of RichTextBox, I'm using this at moment:
public void SortLines(object sender, EventArgs e)
{
TextPointer pStart = TextInput.Document.ContentStart;
TextPointer pEnd = TextInput.Document.ContentEnd;
TextRange text = new TextRange(pStart, pEnd);
string[] lines = text.Text.Split('\n');
Array.Sort(lines);
text.Text = String.Join(String.Empty, lines);
}
Is there an best way to do this?
When I call it, the cursor is placed into first RichTextBox line, how do I to put it where it was before? I tried to set pStart/pEnd and CaretPositiom, but the properties are read only.
I hope this is clear. Thanks in advance.
回答1:
An inelegant but practical solution; back and forth richtextbox to ListBox : In the properties on your listBox you click 'sorted'> true
[c#]
ListBox1.Items.AddRange(RichTextBox1.Lines);
for (int x = 0; (x
<= (ListBox1.Items.Count - 1)); x++) {
RichTextBox1.AppendText((ListBox1.Items(x).ToString.Environment.NewLine));
}
[VB.NET]
ListBox1.Items.AddRange(RichTextBox1.Lines)
For x As Integer = 0 To ListBox1.Items.Count - 1
RichTextBox1.AppendText(ListBox1.Items(x).ToString & Environment.NewLine)
Next
回答2:
As far is it comes to sorting this solution is not to different from you suggested one, but I find it more elegant + it handles cursor location & selection:
public void SortLines(object sender, EventArgs e)
{
rtb.HideSelection = false; //for showing selection
/*Saving current selection*/
string selectedText = rtb.SelectedText;
/*Saving curr line*/
int firstCharInLineIndex = rtb.GetFirstCharIndexOfCurrentLine();
int currLineIndex = rtb.Text.Substring(0, firstCharInLineIndex).Count(c => c == '\n');
string currLine = rtb.Lines[currLineIndex];
int offset = rtb.SelectionStart -firstCharInLineIndex;
/*Sorting*/
string[] lines = rtb.Lines;
Array.Sort(lines, delegate(string str1, string str2) { return str1.CompareTo(str2); });
rtb.Lines = lines;
if (!String.IsNullOrEmpty((selectedText)))
{
/*restoring selection*/
int newIndex = rtb.Text.IndexOf(selectedText);
rtb.Select(newIndex, selectedText.Length);
}
else
{ /*Restoring the cursor*/
//location of the current line
int lineIdx = Array.IndexOf(rtb.Lines, currLine);
int textIndex = rtb.Text.IndexOf(currLine);
int fullIndex = textIndex + offset;
rtb.SelectionStart = fullIndex;
rtb.SelectionLength = 0;
}
}
回答3:
Thanks Eric Paroissien for your simple solution! The C# code had a couple of issues - Here's his solution with the fix
ListBox1.Items.Clear();
ListBox1.Items.AddRange(RichTextBox1.Lines);
RichTextBox1.Clear();
for (int x = 0; (x <= (ListBox1.Items.Count - 1)); x++)
{
RichTextBox1.AppendText(ListBox1.Items[x].ToString());
RichTextBox1.AppendText(Environment.NewLine);
}
来源:https://stackoverflow.com/questions/9009353/what-is-best-way-to-sort-lines-in-richtextbox