Filter ListBox with TextBox in realtime(使用 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();
}
以下是问题:
当我运行程序时,我得到这个错误:
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
.您需要保存在某处的项目"集合(Dictionary
、DataBase
、XML
、BinaryFile
、Collection
),简称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
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01