Home >Backend Development >C++ >How to Implement Flexible AutoComplete Functionality Beyond Prefix Matching in C#?

How to Implement Flexible AutoComplete Functionality Beyond Prefix Matching in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-01 06:41:09296browse

How to Implement Flexible AutoComplete Functionality Beyond Prefix Matching in C#?

Implementing Flexible AutoComplete for C

In C#, when adding auto-completion functionality to a text box, the existing solution only allows searching based on a prefix. To overcome this limitation and enable more flexible search options, custom implementation is necessary.

One approach is to override the OnTextChanged event and implement a custom auto-complete logic. This can be achieved by creating a list view below the text box and populating it dynamically based on user input.

For example, here is a rudimentary implementation:

public Form1()
{
    InitializeComponent();

    acsc = new AutoCompleteStringCollection();
    textBox1.AutoCompleteCustomSource = acsc;
    textBox1.AutoCompleteMode = AutoCompleteMode.None;
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}

private void button1_Click(object sender, EventArgs e)
{
    acsc.Add("[001] some kind of item");
    acsc.Add("[002] some other item");
    acsc.Add("[003] an orange");
    acsc.Add("[004] i like pickles");
}

void textBox1_TextChanged(object sender, System.EventArgs e)
{
    listBox1.Items.Clear();
    if (textBox1.Text.Length == 0)
    {
    hideResults();
    return;
    }

    foreach (String s in textBox1.AutoCompleteCustomSource)
    {
    if (s.Contains(textBox1.Text))
    {
        Console.WriteLine("Found text in: " + s);
        listBox1.Items.Add(s);
        listBox1.Visible = true;
    }
    }
}

void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
    hideResults();
}

void listBox1_LostFocus(object sender, System.EventArgs e)
{
    hideResults();
}

void hideResults()
{
    listBox1.Visible = false;
}

This approach allows you to search for items regardless of their position in the string. You can further enhance the implementation by adding additional features such as text appending, capturing keyboard commands, and more.

The above is the detailed content of How to Implement Flexible AutoComplete Functionality Beyond Prefix Matching in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn