C#WinForms ListBox增量搜索,键/值对为ListItems

时间:2016-08-03 07:54:34

标签: c# winforms listbox incremental-search

我已经搜索了一个答案,虽然有一个在使用带有字符串类型的项目的列表框时有效,但我无法弄清楚当我的项目类型为

KeyValuePair<string, ChangeRec>

我希望能够在列表框中键入时进行搜索(不能使用ComboBox,因为控件需要在表单上具有特定大小),通过键(文本)项进行搜索。感谢@Marcel Popescu的起点。这是我的代码版本(仅在其失败的行上方进行了评论,因为它正确地将kvp项目转换为字符串):

private string searchString;
private DateTime lastKeyPressTime;

private void lbElementNames_KeyPress(object sender, KeyPressEventArgs e)
{
    this.IncrementalSearch(e.KeyChar);
    e.Handled = true;
}

private void IncrementalSearch(char ch)
{
    if ((DateTime.Now - this.lastKeyPressTime) > new TimeSpan(0, 0, 1))
    {
        this.searchString = ch.ToString();
    }
    else
    {
        this.searchString += ch;
    }
    this.lastKeyPressTime = DateTime.Now;
    //* code falls over HERE *//
    var item =
        this.lbElementNames.Items.Cast<string>()
            .FirstOrDefault(it => it.StartsWith(this.searchString, true, CultureInfo.InvariantCulture));

    if (item == null) return;
    var index = this.lbElementNames.Items.IndexOf(item);
    if (index < 0) return;        
    this.lbElementNames.SelectedIndex = index;
}

1 个答案:

答案 0 :(得分:1)

使用此功能,我假设您要搜索的是Key的{​​{1}}:

KeyValuePair

由于KeyValuePair是一个值类型,因此它不能为null。要确定是否已为其分配值,请使用//* code falls over HERE *// var item = this.lbElementNames.Items.Cast<KeyValuePair<string, ChangeRec>>() .FirstOrDefault(it => it.Key.StartsWith(this.searchString, true, CultureInfo.InvariantCulture)); if (item.Equals(default(KeyValuePair<string, ChangeRec>))) return;

进行检查
相关问题