使用 TextBox 实时过滤 ListBox

Filter ListBox with TextBox in realtime(使用 TextBox 实时过滤 ListBox)

本文介绍了使用 TextBox 实时过滤 ListBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自文本框的文本实时过滤列表框.

I am trying to filter an listbox with text from a textbox, realTime.

代码如下:

private void SrchBox_TextChanged_1(object sender, EventArgs e)
{
  var registrationsList = registrationListBox.Items.Cast<String>().ToList();
  registrationListBox.BeginUpdate();
  registrationListBox.Items.Clear();
  foreach (string str in registrationsList)
  {
    if (str.Contains(SrchBox.Text))
    {
      registrationListBox.Items.Add(str);
    }
  }
  registrationListBox.EndUpdate();
}

以下是问题:

  1. 当我运行程序时,我得到这个错误:Object reference not set to an instance of an object

如果我按退格键,我的初始列表将不再显示.这是因为我的实际项目列表现在减少了,但我该如何实现呢?

If I hit backspace, my initial list is not shown anymore. This is because my actual list of items is now reduced, but how can I achieve this?

你能指出我正确的方向吗?

Can you point me in the right direction?

推荐答案

很难从代码中推断出来,但我推测你的过滤问题来自不同方面:

It's hard to deduct just from the code, but I presume your filtering problem born from the different aspects:

a) 您需要 ListBox 上显示的数据的 Model.您需要保存在某处的项目"集合(DictionaryDataBaseXMLBinaryFileCollection),简称​​Store.

a) You need a Model of the data shown on ListBox. You need a colleciton of "Items" which you hold somewhere (Dictionary, DataBase, XML, BinaryFile, Collection), some kind of Store in short.

要在 UI 上显示数据,您总是从该 Store 中挑选数据,对其进行过滤并将其放在 UI 上.

To show the data on UI you always pick the data from that Store, filter it and put it on UI.

b) 在第一点之后,您的过滤代码可能如下所示(伪代码)

b) After the first point your filtering code can look like this (a pseudocode)

var registrationsList = DataStore.ToList(); //return original data from Store

registrationListBox.BeginUpdate();
registrationListBox.Items.Clear();

if(!string.IsNullOrEmpty(SrchBox.Text)) 
{
  foreach (string str in registrationsList)
  {                
     if (str.Contains(SrchBox.Text))
     {
         registrationListBox.Items.Add(str);
     }
  }
}
else 
   registrationListBox.Items.AddRange(registrationsList); //there is no any filter string, so add all data we have in Store

registrationListBox.EndUpdate();

希望这会有所帮助.

这篇关于使用 TextBox 实时过滤 ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 TextBox 实时过滤 ListBox

基础教程推荐