Kinjan Bhavsar
Kinjan Bhavsar

Reputation: 1449

How to access Contacts in Windows 10 UWP?

I want to access Contacts Data and so I did some research and found the following article from MSDN

Accessing Contacts

From this article, I read selecting multiple contacts section and I used that but every time, the Emails and Phones value is null.

My code to access contact is below:

var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();
contactPicker.CommitButtonText = "Select";
contacts = await contactPicker.PickContactsAsync();

PhoneContactsList.Items.Clear();

if (contacts != null && contacts.Count > 0)
{
    PhoneContactsList.Visibility = Windows.UI.Xaml.Visibility.Visible;
    foreach (Contact contact in contacts)
    {
        ContactData eachContact = new ContactData();
        eachContact.DisplayName = contact.DisplayName;
        if (contact.Emails.Count > 0)
        {
            eachContact.EmailAddress = contact.Emails[0].Address;
        }
        else if (contact.Phones.Count > 0)
        {
            eachContact.PhoneNumber = contact.Phones[0].Number;
        }
        contactsData.Add(eachContact);
    }
    PhoneContactsList.ItemsSource = contactsData;
}

Please suggest what I am doing wrong here?

Update

When I debug the code and check I can't see any values, only thing shown is System._ComObject. I don't know what it means.

Upvotes: 3

Views: 1536

Answers (1)

Konstantin
Konstantin

Reputation: 884

You need to filter contacts by requested fields:

var contactPicker = new ContactPicker();
contactPicker.CommitButtonText = "Select";
contactPicker.SelectionMode = ContactSelectionMode.Fields;
contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.Email);

var contacts = await contactPicker.PickContactsAsync();
if (contacts != null && contacts.Count > 0)
{
    foreach (Contact contact in contacts)
    {
        Debug.WriteLine(contact.DisplayName + contact.Emails[0].Address);
    }
}

p.s. System._ComObject is internal native object. You have to turn on native debugging to work with it.

Upvotes: 3

Related Questions