Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16300

Filter a dropdown list

I have a dropdown list bound to a list of objects. The list can have over 20000 items. I do not want to populate the list immediately. However, when the user types in the text portion of the list, the control should start filtering the list and display matching items.

I was trying the following:

    private void cboName_TextChanged(object sender, EventArgs e)
    {
        var query1 = allNames.Where(x => x.firstname.Contains(cboName.Text) || x.lastname.Contains(cboName.Text)).ToList();

        cboName.DataSource = query1;
        cboName.ValueMember = "id";
        cboName.DisplayMember = "firstname";
    }

But it doesn't work performance-wise. Is there a way to achieve this?

Upvotes: 0

Views: 1524

Answers (2)

CodeTherapist
CodeTherapist

Reputation: 2806

You can stick with your code that you already have.

private void cboName_TextChanged(object sender, EventArgs e)
    {
        var query1 = allNames.Where(x => x.firstname.Contains(cboName.Text) || x.lastname.Contains(cboName.Text)).ToList();

        cboName.DataSource = query1;
        cboName.ValueMember = "id";
        cboName.DisplayMember = "firstname";
    }

You can set a delay, before you filter, or use the keydown with a listen to the enter Key and than filter the list.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

For your requirement you can try out this

TextBox.AutoCompleteMode Property

Example :

private void Form1_Load(object sender, EventArgs e)
{
    // Create the list to use as the custom source.  
    var source = new AutoCompleteStringCollection();
    source.AddRange(new string[]
                    {
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December"
                    });

    // Create and initialize the text box. 
    var textBox = new TextBox
                  {
                      AutoCompleteCustomSource = source,
                      //Appends both Suggest and Append options.
                      AutoCompleteMode = 
                          AutoCompleteMode.SuggestAppend,
                      AutoCompleteSource =
                          AutoCompleteSource.CustomSource,
                      Location = new Point(20, 20),
                      Width = ClientRectangle.Width - 40,
                      Visible = true
                  };

    // Add the text box to the form.
    Controls.Add(textBox);
}

Upvotes: 1

Related Questions