我如何筛选的基础上投入一个TextBox一个ListBox? [英] How do I filter a ListBox based on input from a TextBox?

查看:183
本文介绍了我如何筛选的基础上投入一个TextBox一个ListBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的编程,我需要就如何通过在 C#应用程序使用文本过滤列表框的帮助。

i am new in programing i need help regarding how to filter listbox via using textbox in c# application.

我的意思是输入一些文字到文本框和过滤同时在列表框中,如果在列表中的项目退出,然后选择到其他文本框打开了新形式的创造和蔼的项目给我的例子是一样的。

I mean enter some text into textbox and filter same time in listbox if items exits in lists then select into textbox else open new form for creating the items kindly give me example for the same.

推荐答案

下面是一个简单的自动完成的文本框,你应该能够使用以满足您的需求:

Here is a simple autocomplete textbox you should be able to use to fit your needs:

class AutoSuggestControl : TextBox
{
    List<string> Suggestions;
    int PreviousLength; 

    public AutoSuggestControl() : base()
    {
        Suggestions = new List<string>();

        // We keep track of the previous length of the string
        // If the user tries to delete characters we do not interfere
        PreviousLength = 0; 

        // Very basic list, too slow to be suitable for systems with many entries
        foreach(var e in yourListbox.Items)
        {
            //add your listbox items to the textbox
        }
        Suggestions.Sort();
    }

    /// <summary>
    /// Search through the collection of suggestions for a match
    /// </summary>
    /// <param name="Input"></param>
    /// <returns></returns>

    private string FindSuggestion(string Input)
    {
        if (Input != "")
        foreach (string Suggestion in Suggestions)
        {
            if (Suggestion.StartsWith(Input))
                return Suggestion;
        }
        return null;
    }

    /// <summary>
    /// We only interfere after receiving the OnTextChanged event.
    /// </summary>
    /// <param name="e"></param>
    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);

        // We don't do anything if the user is trying to shorten the sentence
        int CursorPosition = SelectionStart;
        if (Text.Length > PreviousLength && CursorPosition >= 0)
        {
            string Suggestion = FindSuggestion(Text.Substring(0, CursorPosition));
            if (Suggestion != null)
            {
                // Set the contents of the textbox to the suggestion
                Text = Suggestion;
                // Setting text puts the cursor at the beginning of the textbox, so we need to reposition it
                Select(CursorPosition, 0);
            }
        }
        PreviousLength = Text.Length;
    }

}

这篇关于我如何筛选的基础上投入一个TextBox一个ListBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆