65.9K
CodeProject 正在变化。 阅读更多。
Home

创建带有搜索和建议列表的组合框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (9投票s)

2014 年 6 月 25 日

CPOL

1分钟阅读

viewsIcon

57508

downloadIcon

42

如何创建一个带有搜索和建议列表的组合框

引言

本文档将指导您创建可以搜索并具有建议列表的组合框。

下载 ComboboxWithSearching.rar

背景

通常情况下,当组合框中包含大量项目时,添加搜索功能和建议列表可能是一个很好的增强。

在组合框中进行搜索最基本的方法是利用自动完成功能,但它只表现出 string.StartWith() 搜索,并且无法覆盖该功能。因此,为了让组合框在任何您想要的地方进行搜索,并像自动完成一样具有建议列表,我们需要另一种方法。

使用代码

我们将使用列表框来模拟自动完成的建议列表。首先,我们在组合框下方添加一个列表框(使用属性面板中的 Location 属性可能更容易实现)。

然后,我们希望组合框在每次键入内容时都进行搜索,因此我们处理组合框的 TextChanged 事件(TextUpdated 也可以)。

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    // get the keyword to search
    string textToSearch = comboBox1.Text.ToLower();
    listBox1.Visible = false; // hide the listbox, see below for why doing that
    if (String.IsNullOrEmpty(textToSearch))
        return; // return with listbox hidden if the keyword is empty
    //search
    string[] result = (from i in collections
            where i.ToLower().Contains(textToSearch)
            select i).ToArray();
    if (result.Length == 0)
        return; // return with listbox hidden if nothing found

    listBox1.Items.Clear(); // remember to Clear before Add
    listBox1.Items.AddRange(result);
    listBox1.Visible = true; // show the listbox again
}

之后,当我们输入组合框时,列表框会显示搜索结果(请注意搜索不区分大小写)。

然后,我们希望当用户单击建议列表中的一个项目时,列表消失并且该项目显示在组合框中;我们将处理列表框的 SelectedIndexChanged 事件。

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    comboBox1.SelectedItem = listBox1.SelectedItem;
    listBox1.Visible = false;
}

这里组合框显示与列表框相同的项目类型,因此代码很短(您应该已经处理了组合框的 SelectedIndexChanged 事件)。

完成了!一个带有搜索和建议列表的组合框,在您键入时就能看到!

关注点

将列表框作为建议列表的主要思想可以在更广泛的上下文中扩展,例如带有自定义自动完成功能的文本框,或者通过图像建议项目的搜索框。

历史

版本 1.1

© . All rights reserved.