【发布时间】:2014-10-23 14:27:33
【问题描述】:
我找到了以下代码 http://www.dotnetcurry.com/showarticle.aspx?ID=146 并将其实现到我的应用程序中,但是它只找到一次字符串并继续查找字符串的其他实例,您必须按住搜索按钮(100 次匹配有点乏味)。
我想找到搜索字符串的所有实例,如果可能的话,突出显示每一行,如果没有像这段代码那样突出显示字符串项,但所有实例不只是一个。
在上面的链接中,页面下方可能有一个解决方案,但它是在 VB 中,我不知道如何转换为 C#。
private void btnListSearch_Click(object sender, EventArgs e)
{
int startindex = 0;
if (txtSearch.Text.Length > 0)
startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
rtb.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
rtb.Focus();
rtb.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
rtb.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >=0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
// Reset the richtextbox when user changes the search string
start = 0;
indexOfSearchText = 0;
}
我也尝试搜索一个列表框,但它只会在行首而不是沿行找到字符串。
string searchString = textBox2.Text;
listBoxResults.SelectionMode = SelectionMode.MultiExtended;
// Set our intial index variable to -1.
int x = -1;
// If the search string is empty exit.
if (searchString.Length != 0)
{
// Loop through and find each item that matches the search string.
do
{
// Retrieve the item based on the previous index found. Starts with -1 which searches start.
x = listBoxResults.FindString(searchString, x);
// If no item is found that matches exit.
if (x != -1)
{
// Since the FindString loops infinitely, determine if we found first item again and exit.
if (listBoxResults.SelectedIndices.Count > 0)
{
if (x == listBoxResults.SelectedIndices[0])
return;
}
// Select the item in the ListBox once it is found.
listBoxResults.SetSelected(x, true);
}
} while (x != -1);
}
【问题讨论】:
-
请正确缩进代码以获得更好的可读性。
标签: c# listbox richtextbox