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

时间:2011-01-05 23:03:20

标签: c# search listbox

我搜索了网站但找不到答案。

我有一个名为“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)

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

代码是C#和软件VS 2008 Pro

由于

3 个答案:

答案 0 :(得分:4)

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

foreach (var item in ListBox.Items)
{
    if (item.Text.Contains(searchArg))
    {
        //select this item in the ListBox.
        ListBox.SelectedValue = item.Value;
        break;
    }
} 

答案 1 :(得分:1)

1. /创建一个包含您要搜索的属性的对象     在
    2. /将您的项目添加为对象而不是字符串
    3. /使用您要显示的格式覆盖ToString()     列表框
    4. /使用Linq根据需要查询对象。

var result = from o in ListBox.Items.OfType<yourClass>()
             where o.Whatever == yourCriteria
             select o;

答案 2 :(得分: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