首页 文章

搜索ListBox并在C#中选择结果

提问于
浏览
1

我搜索过网站但找不到答案 .

我有一个名为“CompetitorDetailsOutput”的列表框然后我在上面有一个名为“searchbox”的文本框和一个名为“searchbutton”的按钮列表框中的数据会不断更改并从.txt文件中获取数据,并以下列格式存储数据

string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, TotalSingleScore);

列表框然后显示如下

string.Format("{0,-20}|{1,-10}|{2,-9}|{3,-7}|{4,2}|{5,2}|{6,2}|{7,2}|{8,2}|{9,2}|{10,2}|{11,2}|{12,3}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, TotalSingleScore)

我希望能够按如下方式搜索列表框:用户只将数据输入“搜索框”并按“搜索按钮”,系统然后搜索列表框,如果它发现它选择列表框中的项目,如果没有,那么紧密匹配是选中,如果没有紧密匹配,则显示错误消息 .

Code is C# and software VS 2008 Pro

谢谢

3 回答

  • 1

    尝试这样的方法来启动“匹配”算法:

    foreach (var item in ListBox.Items)
    {
        if (item.Text.Contains(searchArg))
        {
            //select this item in the ListBox.
            ListBox.SelectedValue = item.Value;
            break;
        }
    }
    
  • 4
    1. /创建一个包含要搜索的属性的对象
    2. /将您的项目添加为对象而不是字符串
    3. /使用要在列表框中显示的格式覆盖ToString()
    4. /使用Linq根据需要查询对象 .
    var result = from o in ListBox.Items.OfType<yourClass>()
                 where o.Whatever == yourCriteria
                 select o;
    
  • 1
    private void FindAllOfMyString(string searchString)
        {
            // Set the SelectionMode property of the ListBox to select multiple items.
            ListBox.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 = ListBox.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 (ListBox.SelectedIndices.Count > 0)
                        {
                            if (x == ListBox.SelectedIndices[0])
                                return;
                        }
                        // Select the item in the ListBox once it is found.
                        ListBox.SetSelected(x, true);
                    }
                } while (x != -1);
            }
        }
    
    private void Srchbtn_Click(object sender, EventArgs e)
        {
            FindAllOfMyString(SrchBox.Text);
        }
    

    http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.findstring(v=vs.71).aspx

相关问题