I have a TextBox to search all occurences of the entered text in RichTextBox Control. The result will be populated in a listbox for traversal pupose after the search gets over.
I have written following function to achieve thedesired result.. but its taking good amount of time to complete.. I need some suggestion to fix this issue
In short I need to implement FindAll feature..
public void FindSearchResults(string searchWord)
{
CheckState matchCase = default(CheckState);
CheckState matchWholeWords = default(CheckState);
RichTextBox tvc = this._rt;
List<string> retVal = new List<string>();
RichTextBoxFinds FindOptions = default(RichTextBoxFinds);
currentSearchWord = searchWord;
FindOptions = RichTextBoxFinds.None;
// Location to begin the search.
FindOptions = RichTextBoxFinds.None;
int searchResult = -2;
int start = 0;
string expandedValue = "";
if ((matchWholeWords == CheckState.Checked) & (matchCase == CheckState.Checked))
{
FindOptions = RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord;
}
else if ((matchWholeWords == CheckState.Checked))
{
FindOptions = RichTextBoxFinds.WholeWord;
}
else if ((matchCase == CheckState.Checked))
{
FindOptions = RichTextBoxFinds.MatchCase;
}
else
{
FindOptions = RichTextBoxFinds.None;
}
while (searchResult != -1 & start < tvc.Text.Length)
{
searchResult = tvc.Find(searchWord, start, FindOptions);
if ((searchResult != -1))
{
expandedValue = Expand(searchWord, searchResult);
while (searchResultList.ContainsKey(expandedValue))
{
// just to keep uniqueness
expandedValue = expandedValue + " ";
}
retVal.Add(expandedValue);
searchResultList[expandedValue] = searchResult;
start = searchResult + searchWord.Length;
}
}
}
private string Expand(string searchWord, int searchResult)
{
string retVal = null;
int startPos = 0;
int endPos = 0;
int spaceCount = 0;
RichTextBox tvc = this._rt;
startPos = searchResult;
spaceCount = 0;
while (spaceCount < 2 & startPos > 0)
{
startPos = startPos - 1;
char[] ch=tvc.Text.Substring(startPos,1).ToCharArray();
if (ch[0] == (Char)32)
{
spaceCount = spaceCount + 1;
}
}
spaceCount = 0;
endPos = searchResult + 1;
while (spaceCount < 4 & endPos < tvc.Text.Length)
{
int asciiVal = 0;
asciiVal = Strings.Asc(tvc.Text.Substring(endPos,1));
if (asciiVal == 10 | asciiVal == 13 | asciiVal == 32)
{
spaceCount = spaceCount + 1;
}
endPos = endPos + 1;
}
retVal = tvc.Text.Substring(startPos, endPos - startPos);
retVal = retVal.Replace(Environment.NewLine, string.Empty);
return retVal;
}