Reputation: 3755
Keynotfound exception
public int getLastUniqueID()
{
int lastID = 0;
IsolatedStorageSettings uc = IsolatedStorageSettings.ApplicationSettings;
List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];
foreach (sMedication temp in medicationList) {
lastID = temp.UniqueID;
}
return lastID;
}
It is happening on the following line:
List<sMedication> medicationList = (List<sMedication>)uc["medicationList"];
Upvotes: 0
Views: 176
Reputation: 950
You're going to run into problems with that approach because, if the key "medicationList" isn't there in the retrieved Application Settings, then it'll throw an exception like you have witnessed.
Try the following:
uc.TryGetValue<List<sMedication>>("medicationList", out medicationList)
if (medicationList != null)
{
foreach(sMedication temp in medicationList)
{
lastID = temp.UniqueID;
return lastID;
}
}
else
{
// handle the key not being there
}
Upvotes: 1
Reputation: 36
As the error indicate that key was not found in the dictionary before accessing the value check if the key exists or not
if(uc.Contains("medicationList"))
{
// your code here
}
Upvotes: 2