Veleje
Veleje

Reputation: 15

reading from text box and passing to another page

I want to read text from TextBox and then send it to another page. But on another page I keep geting empty string. why this doesn't work ?

I have this on page 1:

public string _beseda()
{
    return textBox1.Text;          
}

and on page 2 where I should retrieve this string:

private void button1_Click(object sender, RoutedEventArgs e)
{
    Page2 neki = new Page2();
    MessageBox.Show(neki._beseda());
}

Upvotes: 0

Views: 2708

Answers (2)

Seth Kigen
Seth Kigen

Reputation: 101

There are two strategies to pass data between pages in windows phone.

  1. Use App.cs
  2. Pass data as parameter values during navigation

1. Using App.cs

Open up App.cs code behind of App.xaml write:

 // To store Textbox the value   
 public string storeValue;

In Page1

 protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        App app = Application.Current  as App;
        app.storeValue = textBox1.Text;            
    }

on Page2

 private void button1_Click(object sender, RoutedEventArgs e) {

    App app = Application.Current  as App;
    MessageBox.Show(app.storeValue);
}

2. Passing values as parameters while navigating

Before navigating embed textbox value to the Page Url

    string newUrl = "/Page2.xaml?text="+textBox1.Text;
    NavigationService.Navigate(new Uri(newUrl, UriKind.Relative));

in Page2

    //Temporarily hold the value got from the navigation 
    string textBoxValue = "";
    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        //Retrieve the value passed during page navigation
         NavigationContext.QueryString.TryGetValue("text", out textBoxValue)               
    }


     private void button1_Click(object sender, RoutedEventArgs e) {

       MessageBox.Show(textBoxValue);
     }

Here are a number of useful links..

Upvotes: 1

tnw
tnw

Reputation: 13877

There's a number of issues. You say you have that _beseda() function on Page1, but you reference Page2() in button1_click(). Additionally, if I assume you meant Page1 in button1_click(), you're creating newPage1 and then you ask it for the text box's text.... so of course it's empty. You haven't put anything in it.

Even if you meant to put Page2 there instead, the problem is still the same.

Upvotes: 1

Related Questions