简体   繁体   中英

How can I get a dynamically generated drop down choices for a text field in C#?

I want to have a text field in a C# winform application, and the effect I want is that as the user types stuff in the text field, the program searches a database in the background, and then generates a drop down list for the user to choose from ..

Here are two web based examples but do note that my application is winforms based, not web-based .. I just want the same effect, which is why I'm showing these:

cinemasquid.com:

cinemasquid.com:

blu-ray.com:

blu-ray.com:

How can I get the same effect for a text field in a C# winform application ?

First you will need to bind TextChanged event on the form. Then when user press any key, you will get the event. Now inside event handler retrieve the string entered by the user, using this string you perform the search (don't do the search on UI thread, else your UI will hang, you can do the search in BackgroudWorker ( MSDN )). Once you get the result, bind this result to ListBox .

I had developed one application, which has autocomplete feature. In this if user enter any movie name, matching results use to be displayed in the list box.

在此处输入图片说明

Hope this works for you.

If you don't want to code your solution there are a handful of custom controls avaliable via Google search, for example: http://www.dotnetfunda.com/articles/article225.aspx

BUT you should keep response times in mind: if you code a database search everytime the user enters a letter on your textbox, your application could get sluggish and/or unresponsive, depending on number of records on the table, speed of your network connection and a lot of other factors.

Consider preloading a collection of strings (name, titles, whatever it is you want to display on the textbox) on memory and then performing LINQ queries to that in-memory collection to populate the autocomplete part of your control.

As Amar Palsapure say, You need to use TextChanged Event of You DropDown. Also, Background worker will be also welcome. Here is a short example:

First, we need some data source. In this case, this will be a simple list of strings:

List<string> DataSource = new List<string>
{
   " How do I use jQuery to select all children except a select element",
    "How can I get the text of the selected item from a dropdown using jQuery?",
    "Dropdown menu in IE6 inserting too much width, not dropping-down",
    "How to display images within a drop down box instead of text",
    "InfoPath 2007 - Populate drop-down list on-the-fly",
    "Is there any difference between drop down box and combo box?",
    "Drop Down list null value not working for selected text c#?",
    "Make drop-downs automatically drop in a loop cycle",
    "PHP How can I keep the selected option from a drop down to stay selected on submit?",
    "Jquery Issue - Drop down list does NOT show from iPhone/Mobile Devices"
};

next, BackgroundWorker DoWork Event - this is part response for searching valid position in our Data Source:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        String text = e.Argument as String;
        List<String> results = new List<string>();

        //Code for seraching text - may be diffrent if you have another DataSource 
        foreach (String dataString in DataSource)
        {
            if (dataString.IndexOf(text, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
            {
                results.Add(dataString);
            }
        }
        e.Result = results;
    }

You can see, that Result is returning by e.Result , So we need to implement RunWorkerCompleted event too:

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        comboBox1.Items.AddRange((e.Result as List<String>).ToArray());
        comboBox1.DroppedDown = true;
    }

This code will fill our dropDown witch returned values, and show it to user.

Of course, to make this run, you need to call RunWorkerAsync in TextChanged :

    private void comboBox1_TextChanged(object sender, EventArgs e)
    {
        // Save position of cursor, because it like to dissapering.
        int cursor = comboBox1.SelectionStart;
        //Clearing items in dropDown 
        comboBox1.Items.Clear();

        //Is something was searched before, cancel it!
        while (backgroundWorker1.IsBusy)
        {
            if (!backgroundWorker1.CancellationPending)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        // And search new one 
        backgroundWorker1.RunWorkerAsync(comboBox1.Text);

        // And bring back cursor to live
        comboBox1.SelectionStart = cursor;
    }

I hope that helped you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM