How do I grab the contact list of a windows 7 phone for use inside a win7 phone app?
With the earlier version of the Windows Phone 7 SDK, it was only possible to retrieve the phone number or email address and a few more with the Choosers. Now, with the 7.1 Mango SDK, it is possible to retrieve more information from the contact, like Address, DisplayName, EmailAddresses etc.
I will show you how to retrieve all contacts from Windows Phone 7 using C#.
The Contacts Class is defined in the namespace Microsoft.Phone.UserData and extends from PhoneDataSharingContext and provides a few methods and events for interacting with a user’s contact data.
public MainPage()
{
InitializeComponent();
Contacts objContacts = new Contacts();
objContacts.SearchCompleted += new EventHandler(objContacts_SearchCompleted);
objContacts.SearchAsync(string.Empty, FilterKind.None, null);
}
void objContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
foreach (var result in e.Results)
{
lst.Add("Name : " + result.DisplayName + " ; Phone Number : " + result.PhoneNumbers.FirstOrDefault());
}
}
Contacts can also enable the user to search for the contact with the SearchAsync method. The FilterKind determines the field that will be used for filtering like PhoneNumber, DisplayName or EmailAddress etc. When it is None, it can list all the contacts.
Note that I have used the emulator since I don't have the device with Mango currently.
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Contacts objContacts = new Contacts();
objContacts.SearchCompleted += new EventHandler(objContacts_SearchCompleted);
objContacts.SearchAsync(string.Empty, FilterKind.None, null);
}
void objContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
var ContactsData = from m in e.Results
select new MyContacts
{
DisplayName = m.DisplayName,
PhoneNumber = m.PhoneNumbers.FirstOrDefault()
};
var MyContactsLst = from contact in ContactsData
group contact by contact.DisplayName into c
orderby c.Key
select new Group(c.Key, c);
longlist1.ItemsSource = ContactsData;
}
}
public class MyContacts
{
public string DisplayName { get; set; }
public ContactPhoneNumber PhoneNumber { get; set; }
}