Passing Data to Pages in Windows Phone 7

In this article, we will discuss how to send our data or information from one page to another in Windows Phone 7. This includes an example in which we send the contents of a TextBox in a page to the TextBox of another page. For that use the following steps.

Step 1: First we click on: File -> New Project -> Windows Phone Application.

After that we set its name and the location of where we want to save it.

Step 2: After that we create a TextBlock in the ContentPanel like this:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Text="Passing data to the Page1" HorizontalAlignment="Center" VerticalAlignment="Center"
ManipulationStarted="TextBlock_ManipulationStarted"
   ></TextBlock
>
</Grid>

Step 3: Now we take a TextBox ( In this example we send the data of this TextBox to the another Page)
<TextBox Height="72" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="460" />

The output will be:

DataWin1.jpg

Step 4: After that, we add a Windows Phone Page (Page1) to our program. Here again use a TextBox in which we show the data like this:

<TextBox Height="72" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="460" />

Step 5: After that we write the following code in the MainPage.xaml.cs:

private void TextBlock_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
{
    string urlofdestinationpage = "/Page1.xaml";
    urlofdestinationpage += string.Format("?TextData="+ textBox1.Text);
    this.NavigationService.Navigate(new Uri(urlofdestinationpage, UriKind.Relative));
    e.Complete();
    e.Handled = true;
}


Here we call the OnManipulationStarted Event, in which first we assign the URI in a string and then we add the TextBox data in the string.

Step 6: Now we write the following code in the Page1.xaml.cs:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    IDictionary<string, string> x = this.NavigationContext.QueryString;
    String a = Convert.ToString(x["TextData"]);
    textBox1.Text = a.ToString();
    base.OnNavigatedTo(e);
}

Here we use the NavigationContext Property to access the querystring. After that we save the querystring (TextData) in a string valiable and after that we assign it to the the TextBox. Now we get the Data in the TextBox.

The Output will be:

DataWin2.jpg

Then click on the TextBlock (passing data to Page1):

DataWin3.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all