Click here to Skip to main content
Click here to Skip to main content

How to Search for a Contact in WP7 using the Contacts class?

, 4 Apr 2012
Rate this:
Please Sign up or sign in to vote.
How to programmatically search for a specific contact in WP7?

In last two blog posts we learnt how to programmatically Save Contacts in WP7 and Retrieve Contact Information. Now after these, you may want to programmatically search for specific contact. So how to do this?

Windows Phone 7 SDK provides that API for you. You can use that API to asynchronously search for a contact by different parameters. Continue reading the complete post to learn more about the class and search mechanism. Don’t forget to read out my other blog posts too.

Know About the API

The phone 7 SDK provides a sealed class called “Contacts” derived from “PhoneDataSharingContext”. You can find this class in the namespace “Microsoft.Phone.UserData”, which provides a asynchronous method named “SearchAsynch()”. This method takes search query string and kinds of filter as parameter to search for the specific keywords. The “SearchCompleted” event returns the matched contacts to the user.

Here is the meta data of the “Contacts” class:

namespace Microsoft.Phone.UserData
{
    public sealed class Contacts : PhoneDataSharingContext
    {
        public IEnumerable<Account> Accounts { get; }
        public void SearchAsync(string filter, FilterKind filterKind, object state);
        public event EventHandler<ContactsSearchEventArgs> SearchCompleted;
    }
}

The SDK also provides an enum named “FilterKind” which provides filter type for your search query. When set, this will allow you search based on “PinnedToStart”, “EmailAddress”, “PhoneNumber” and “DisplayName”. This is also present in the “Microsoft.Phone.UserData” namespace.

Here is the meta data of the FilterKind enum:

namespace Microsoft.Phone.UserData
{
    public enum FilterKind
    {
        None,
        PinnedToStart,
        EmailAddress,
        PhoneNumber,
        DisplayName,
    }
}

Hope you are now clear about the basic API. Let’s jump start with the implementation of the same.

Implementation Steps

Let us first start creating the UI for our demo with a Search TextBox and a ListBox where the result will be displayed. Now open the MainPage.xaml and modify the ContentPanel as below:

<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <TextBox x:Name="searchBox" TextChanged="ContactsSearchBoxTextChanged"/>
    <ListBox x:Name="contactsList" Height="520">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding DisplayName}" 
                               Style="{StaticResource PhoneTextLargeStyle}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

Now, create the instance of the Contacts class and register for the “SearchCompleted” event. Now do a asynchronous search with empty string in the constructor. This will result out the complete list of contacts in the screen. Set “FilterKind” as DisplayName to search based on the same. Here is the sample code snippet:

// Create instance of Contacts as member object
private readonly Contacts m_contacts = new Contacts();

// Register for "SearchCompleted" event and do Empty Search
m_contacts.SearchCompleted += ContactsSearch;
m_contacts.SearchAsync(string.Empty, FilterKind.DisplayName, null);

In the TextChanged event implementation, call the SearchAsync() method once again but this time pass the search text from the searchTextBox. This will fire the proper search based on the query term.

Let’s have a look into the below code:

private void ContactsSearchBoxTextChanged(object sender, TextChangedEventArgs e)
{
    m_contacts.SearchAsync(searchBox.Text, FilterKind.DisplayName, null);
}

Now in the “SearchCompleted” event implementation, get the e.Results and set it to the ItemsSource of the ListBox. You can do anything here with the data. Make sure that, you bind data in the XAML page correctly.

void ContactsSearch(object sender, ContactsSearchEventArgs e)
{
    try
    {
        // Set the Results to the ItemsSource
        contactsList.ItemsSource = e.Results;
    }
    catch
    {
    }
}

Here is the screenshots of what we implemented as of now. In the first screen you can see all the contacts in the list. When you start typing in the Search TextBox, you will see the filtered Contacts in the list based on what you are typing.

image     image

Hope this post will be helpful for you to understand the API and the basics of contact search. Stay tuned to my blog, Twitter, or Facebook to read more articles, tutorials, news, tips & tricks on various technology fields.

Reference: http://www.kunal-chowdhury.com.

You may like to follow me on twitter @kunal2383 or may like the Facebook page of my blog http://www.facebook.com/blog.kunal2383.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

_ Kunal Chowdhury _
Technical Lead
India India
Kunal Chowdhury is a Microsoft "Client Development" MVP (Most Valuable Professional), a Codeproject Mentor, Telerik MVP, Nokia Developer Champion, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.
 
He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows 8 (WinRT). He posts his findings, articles in his technical blog and CodeProject.
 
Technical Blog: http://www.kunal-chowdhury.com
Facebook: http://facebook.com/blog.kunal
Twitter : http://twitter.com/kunal2383
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionHow to Highlight the searchtext in the result? PinmemberGopinath P23-Dec-12 23:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140902.1 | Last Updated 4 Apr 2012
Article Copyright 2012 by _ Kunal Chowdhury _
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid