I've created an autocomplete textbox on my Winforms application.
private void txtClientName_TextChanged(object sender, EventArgs e)
{
if (txtClientName.Text.Length == 1)
{
completeCollection.Clear();
CustomerRepository repo = new CustomerRepository();
var customers = repo.FindAllCustomers().Where(u => u.Name.StartsWith(txtClientName.Text) || u.LastName.StartsWith(txtClientName.Text));
foreach (var customer in customers)
{
completeCollection.Add(customer.Name + " " + customer.LastName);
}
txtClientName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtClientName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtClientName.AutoCompleteCustomSource = completeCollection;
}
}
When I type in a first name, ie: sergio - it works.
However when I type in a last name, ie: gutierrez - it doesn't fetch the results.
开发者_运维知识库The problem lies in the Query I use against the IQueryable in the FindAllCustomers() method.
What should I change? Also, do you recommend a better way to 'fire' the autocomplete population? Currently, I'm pulling records only when the text length is 1. That's because if someone types in 's' only names or last names that start with s will be loaded.
I have used this Auto Complete Textbox in two or more application. It works fine for me.
The autocomplete system filters your customsource based on what is already typed in. Therefore your lastname matches are not going to be shown.
I suggest you change your current query to only search for Name and not Lastname. After the for each statement you do another query, this time only search for lastname and then execute the for each loop again but change the inner code to:
completeCollection.Add(customer.Lastname + ", " + customer.Name);
This time the textbox should show customers starting with their lastname too.
精彩评论