Get Address from Contact in Windows Phone 7.1 [Mango]


In this article I will show you how to get an address from a contact and display it.

Expected Output

  1. On running of the application you will get a button
  2. On click of the button a contact list will be opened
  3. On selection of a contact the address of that contact will be displayed in a label.

    AddWPhone1.gif

Design the page

I am using a very simple design; it has one button and one label.

On the click event of the button, a contact list will open and on selection of a contact we will display the address of that contact in the label.

The content Grid of the MainPage.Xaml will look like below:

AddWPhone2.gif

Code Behind

Add a namespace:

AddWPhone3.gif

Globally define a variable of type AddressChooserTask:

AddWPhone4.gif

In the constructor of the page create an instance of the AddressChooserTask and register a handler for the completed event on that.

AddWPhone5.gif

In the event, check whether TaskResult is equal to TaskResult enum OK. If yes then display the name and address in the label.

AddWPhone6.gif

Upon click event of the button, we will show the contact:

AddWPhone7.gif

For your reference the full source code of the code behind is as below:

MainPage.Xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks ;
 
namespace AddressChooser
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        AddressChooserTask addressChooserTask;
 
        public MainPage()
        {
            InitializeComponent();
            addressChooserTask = new AddressChooserTask();
            addressChooserTask.Completed += new EventHandler<AddressResult>(addressChooserTask_Completed); 
        } 
        private void addressChooserButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                addressChooserTask.Show();
            }
            catch (System.InvalidOperationException ex)
            {                
            } 
        }      
        void addressChooserTask_Completed(object sender, AddressResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                txtDisplay.Text = "The address for " + e.DisplayName + " is " + e.Address;
            } 
        }
    }
}

Now when you run the phone application you should get the expected output.

I hope this article was useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all