c#

c# textbox如何实现即时搜索

小樊
104
2024-07-23 05:07:04
栏目: 编程语言

要实现即时搜索功能,可以在c#中使用TextBox控件的TextChanged事件来实现。当用户输入文本时,每次文本发生变化时都会触发TextChanged事件,可以在事件处理程序中编写搜索逻辑来实现即时搜索功能。

以下是一个简单示例,演示了如何在TextBox中实现即时搜索功能:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace InstantSearchExample
{
    public partial class Form1 : Form
    {
        private List<string> dataList = new List<string> { "apple", "banana", "orange", "pear", "grape", "cherry" };

        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string searchText = textBox1.Text.ToLower();

            listBox1.Items.Clear();

            foreach (string item in dataList)
            {
                if (item.ToLower().Contains(searchText))
                {
                    listBox1.Items.Add(item);
                }
            }
        }
    }
}

在上面的示例中,我们创建了一个包含若干水果名称的dataList列表,并将其绑定到TextBox的TextChanged事件处理程序中。当用户在TextBox中输入文本时,会根据输入的文本内容动态过滤dataList列表,并将符合条件的结果显示在ListBox中。

通过这种方式,用户可以实时查找并浏览符合搜索条件的结果。

0
看了该问题的人还看了