gpt4 book ai didi

c# - 在列表框中搜索包含字符串的项目

转载 作者:行者123 更新时间:2023-11-30 12:35:03 25 4
gpt4 key购买 nike

背景:我正在构建一个数据库应用程序来存储有关我的大量电影收藏的信息。该列表框包含数百个项目,因此我决定实现一个搜索功能,该功能将突出显示包含特定字符串的所有项目。有时很难记住完整的电影片名,所以我认为这会派上用场。

我在 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);
}
}

最佳答案

创建您自己的搜索功能,类似于

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;
}

(请注意,我是在没有编译或测试的情况下凭头脑写的,代码可能包含错误,但我想你会明白的!!!)

关于c# - 在列表框中搜索包含字符串的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6267368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com