Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Collections.Generic.KeyNotFoundException in Windows Phone

i got a Problem with this following Code:

string name = (string)PhoneApplicationService.Current.State["name"];
names.Add(name);
InitializeComponent();
List.ItemsSource = names;

by:

string name = (string)PhoneApplicationService.Current.State["name"];

i got the error message:

An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code

The Code is in C#. I try to use an Variabel from the othe Page. How can i ask if the variable is "Not found" that the app jump to the other Page? How can i solve the Problem?

like image 748
saaami11 Avatar asked Jan 26 '15 08:01

saaami11


1 Answers

If you want to know whether the key exists before reading it, you can use the ContainsKey method:

if (PhoneApplicationService.Current.State.ContainsKey("name"))
{
    string name = (string)PhoneApplicationService.Current.State["name"];
    names.Add(name);
    InitializeComponent();
    List.ItemsSource = names;
}
else
{
    // Whatever
}

Also, you seem to want to navigate to another page when the key isn't found. The call to InitializeComponent shows that you're executing the code in the page constructor. If you try to use the NavigationService from the constructor, you will have a NullReferenceException. Move the code to the Loaded event, or override the OnNavigatedTo method.

like image 124
Kevin Gosse Avatar answered Oct 18 '22 16:10

Kevin Gosse