【发布时间】:2011-09-10 04:13:05
【问题描述】:
背景:我正在构建一个数据库应用程序来存储有关我的大量电影收藏的信息。列表框包含数百个项目,因此我决定实现一个搜索功能,该功能将突出显示包含特定字符串的所有项目。有时很难记住整个电影的标题,所以我认为这会派上用场。
我在 Microsoft 网站上发现了这个有用的代码,它突出显示了列表框中包含特定字符串的所有项目。如何修改它以完全搜索每个字符串?
目前,该代码仅搜索以搜索字符串开始的项目,而不是查看它是否在其他任何地方包含搜索字符串。我在 Google 上遇到了一种 listbox.items.contains() 方法,尽管我不知道如何为它转换代码。
http://forums.asp.net/t/1094277.aspx/1
private void FindAllOfMyString(string searchString)
{
// Set the SelectionMode property of the ListBox to select multiple items.
listBox1.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 = listBox1.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 (listBox1.SelectedIndices.Count > 0)
{
if(x == listBox1.SelectedIndices[0])
return;
}
// Select the item in the ListBox once it is found.
listBox1.SetSelected(x,true);
}
}while(x != -1);
}
}
【问题讨论】: