Thursday, March 4, 2010

Autocomplete in Silverlight with Visual Studio 2010

Last week I keep searching on how to use the autocomplete in silverligth with visual studio 2010 but most of the examples that I find they are using a textbox or combobox for the autocomplete. I tried to study those examples and apply to the single autocomplete from tools on my silverlight project. And now this is the result. I will use a database again from my previous post (Silverlight Simple DataBinding in DataGrid) to show how the autocomplete works with database.


This is the output:





















First, this is the setup for my autocomplete:

//The tags for autocompletebox on XAML



Second, my simple snippets:

//Event for the autocomplete to send a text string to my function
private void autoCompleteBox1_KeyUp(object sender, KeyEventArgs e)
{
autoCompleteBox1.Populating += (s, args) =>
{
args.Cancel = true;
var c = new Service1Client();
c.GetListByNameCompleted +=new EventHandler(c_GetListByNameCompleted);
c.GetListByNameAsync(autoCompleteBox1.Text);
};
}

//Getting result from database
void c_GetListByNameCompleted(object sender, GetListByNameCompletedEventArgs e)
{
autoCompleteBox1.ItemsSource = e.Result;
autoCompleteBox1.PopulateComplete();
}


The snippets above will show on how to use the autocompleteBox using the data from database that bind in DataGrid. But what if we want to show the result on DataGrid while the autocomplete changing the items source?

Ok just add one line to c_GetListByNameCompleted

void c_GetListByNameCompleted(object sender, GetListByNameCompletedEventArgs e)
{
autoCompleteBox1.ItemsSource = e.Result;
autoCompleteBox1.PopulateComplete();
dataGrid1.ItemsSource = e.Result;
}