3
votes

I'm trying to implement an auto-complete text box on Windows Forms using data from a PostgreSQL database. Let me try to explain my problem:

In the database, I have a table that has firstName and lastName fields separately.

In my Windows Forms application, I want to provide the opportunity to search using either firstName or lastName and provide the AutoComplete options from there.

So for example, if I have an entry on the table with firstName "Goat" and lastName "McGoats", I want to be able to get "Goat McGoats" (firstName {space} lastName) as a suggestion in my Windows Form text box whether I type in "G" or "M" - the start of either first or last names.

Right now, what I have is a working solution for one column (i.e.) I can populate the AutoCompleteSource with the firstName alone (or lastName alone) and then the search would work on that. In the above example, that means typing G would give "Goat" as a suggestion - Note, it does not suggest firstName + lastName.

The current code looks like so:

nameTextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
nameTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();

// Retrieve all rows
cmd.CommandText = "SELECT * FROM users";
using (var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        collection.Add(reader["firstName"].ToString());
    }
}

nameTextBox.AutoCompleteCustomSource = collection;

Does the auto-complete in C# support this feature? Or is adding a hidden listbox below the textbox and populating the values there manually using the search string the only way of doing this?

1

1 Answers

0
votes

No, that is not supported because the implementation depends on IAutoComplete2 which extends IAutoComplete. The textbox prepares all those values from the collection so they can be used by IEnumString and that is about it. All handling is then deferred to the native implementation.

Also none of the AUTOCOMPLETEOPTIONS seem to cater for your use case.

If you don't want to implement what you suggested yourself you could adding both combinations of first and last name. That will double your number of strings but on small sets this might not be a problem. In your loop you change the code to:

// firstname, lastname
collection.Add(String.Format("{0}, {1}",reader["firstName"], reader["lastName"])); 
// lastname, firstname
collection.Add(String.Format("{1}, {0}",reader["firstName"], reader["lastName"])); 

But you might need post processing if you only expect a firstname or a lastname in the textbox.