Reputation: 147
I am trying to count how many times button1 is clicked on page1, then display the amount of clicks on page2 in a textbox1.
I've tried to code below but it is giving me an exception error on the line 'String count= localSettings.Values["Count"].ToString();'.
Is there another way to do what I want to?
Page 1
private void button1_Click(object sender, RoutedEventArgs e)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
String count= localSettings.Values["Count"].ToString();
int tc = int.Parse(count);
tc++;
localSettings.Values["Count"] = tc;
}
Page 2
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
textbox1.Text = localSettings.Values["Count"].ToString();
Upvotes: 1
Views: 72
Reputation: 1026
When you access "Count" for the first time, it does not exist. localSettings.Values["Count"]
is therefore going to be null. You then try to call ToString() on an object that is null and that causes the exception.
Try this:
private void button1_Click(object sender, RoutedEventArgs e)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
int tc = 0;
if( localSettings.Values["Count"] != null )
{
String count= localSettings.Values["Count"].ToString();
tc = int.Parse(count);
}
tc++;
localSettings.Values["Count"] = tc;
}
Upvotes: 2