In this article I will show you how to get an address from a contact and display it.
Expected Output
- On running of the application you will get a button
- On click of the button a contact list will be opened
- On selection of a contact the address of that contact will be displayed in a label.
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:
Code Behind
Add a namespace:
Globally define a variable of type AddressChooserTask:
In the constructor of the page create an instance of the AddressChooserTask and register a handler for the completed event on that.
In the event, check whether TaskResult is equal to TaskResult enum OK. If yes then display the name and address in the label.
Upon click event of the button, we will show the contact:
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.