在列表框中搜索包含字符串的项目 [英] Search listbox for item containing a string
问题描述
背景:我正在构建一个数据库应用程序来存储有关我的大量电影收藏的信息.该列表框包含数百个项目,因此我决定实现搜索功能,该功能将突出显示包含特定字符串的所有项目.有时候很难记住整个电影的标题,所以我认为这会派上用场.
Background: I am building a database application to store information about my massive movie collection. The listbox contains hundreds of items so I decided to implement a search feature which would highlight all items that contain a particular string. Sometimes it's hard to remember an entire movie title so I thought this would come in handy.
我在Microsoft网站上发现了此有用的代码,该代码突出显示了列表框中包含特定字符串的所有项目.如何修改它以完全搜索每个字符串?
I found this useful code on the Microsoft site that highlights all items in a listbox that contain a particular string. How can I modify it to search through each string entirely?
当前,代码仅搜索以搜索字符串开始的项目,而不是查看它是否在其他任何地方包含搜索字符串.我在Google上遇到过listbox.items.contains()这种方法,尽管我不知道如何为它转换代码.
Currently the code only searches for items that start with the search string, instead of seeing if it contains the search string anywhere else. I came across a listbox.items.contains() kind of method on Google, although I have no idea how to convert my code for it.
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);
}
}
推荐答案
创建您自己的搜索功能,类似
Create your own search function, something along the lines of
int FindMyStringInList(ListBox lb,string searchString,int startIndex)
{
for(int i=startIndex;i<lb.Items.Count;++i)
{
string lbString = lb.Items[i].ToString();
if(lbString.Contains(searchString))
return i;
}
return -1;
}
(请注意,我是在不进行编译或测试的情况下写出来的,代码可能包含错误,但是我想您会明白的!!)
(beware, I wrote this out of my head without compiling or testing, the code may contain bugs, but I think you will get the idea!!!)
这篇关于在列表框中搜索包含字符串的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!