I have a small app that reads in a pipe delimted file and writes out lines to a RTB, highlighting if there are dissallowed characters in certain "columns". This is working perfectly...however, the Users want a progress bar and to see the lines being written "live" and also to be able to cancel mid-way through.
I have the following extension method that I have been using to write to a RichTextBox, while blocking the UI, but this fails using a BackgroundWorker with BeginInvoke.
The fail is when finding the current length of the text.
public static void AppendLine(this RichTextBox richTextBox, string text, List<Char> foundChars, List<int> columns)
{
var split = text.Trim().Split(new char[] { '|' });
for (int i = 0; i < split.Count(); i++)
{
**var start = richTextBox.TextLength;**
richTextBox.AppendText(split[i]);
var end = richTextBox.TextLength;
if (columns.Contains(i + 1))
{
foreach (var foundChar in foundChars)
{
var current = start;
while (current > 0)
{
var position = richTextBox.Find(new char[] { foundChar }, current, end);
current = position + 1;
if (current > 0)
{
richTextBox.Select(position, 1);
richTextBox.SelectionColor = Color.Red;
}
}
}
}
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = Color.Black;
}
richTextBox.AppendLine();
}
private void UpdateResultsLine(string line, List<char> foundChars)
{
if (txtResults.InvokeRequired)
{
txtResults.BeginInvoke(new UpdateResultsLineDelegate(UpdateResultsLine), line, foundChars);
}
txtResults.AppendLine(line, foundChars, _fileType.ProcessColumns);
}
However, if I call any/all of these extensions in the same way, they work?
public static void AppendLine(this RichTextBox richTextBox)
{
richTextBox.AppendText(Environment.NewLine);
}
public static void AppendLine(this RichTextBox richTextBox, string text)
{
richTextBox.AppendText(text + Environment.NewLine);
}
public static void AppendLine(this RichTextBox richTextBox, string text, params object[] args)
{
richTextBox.AppendLine(string.Format(text, args));
}
What am I missing? or is there another way to write coloured text to a RTB?