简体   繁体   中英

Argument exception in IsolatedStorageSettings in WP7

In following code, I am getting ArgumentException . This code checks if a key is set in IsolatedStorageSetting . If it is not there , then it is created. At this point the exception is happening with message- value does not fall within the expected range . What wrong I am doing ?

 protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

         var settings = IsolatedStorageSettings.ApplicationSettings;

        if (settings.Contains("bm"))
        {
            string k = (string) settings["bm"];
            if (k == "1")
            {
                cb1.IsChecked = true;
            }
            else
            {
                cb1.IsChecked = false;
            }
        }
        else
        {
            cb1.IsChecked=true;
            settings.Add("bm","1"); //exception occurs here
            settings.Save();
         }
}

As we can see in MSDN

ArgumentException occurs when

key already exists in the dictionary.

So, I can see two problems:

  • Somewhere in the parallel thread the key "bm" is beeng saved to settings.
  • Keys are different. "ь" and "b" are different letters, but they looks similar.

Try to define one constant string:

private const string BM_KEY = "bm";

and use it every time you access to settings.

   if (settings.Contains(BM_KEY))
        {
            string k = (string) settings[BM_KEY];
            if (k == "1")
            {
                cb1.IsChecked = true;
            }
            else
            {
                cb1.IsChecked = false;
            }
        }
        else
        {
            cb1.IsChecked=true;
            settings.Add(BM_KEY,"1"); //exception occurs here
            settings.Save();
        }

to be sure, that you use the same key every time.

Or try to remove the already existing key (example "lastBranoCalled") ;)

if (IsolatedStorageSettings.ApplicationSettings.Remove("lastBranoCalled"))
                    IsolatedStorageSettings.ApplicationSettings.Add("lastBranoCalled", this.Panorama.SelectedIndex.ToString());
                else MessageBox.Show("Error");
            else IsolatedStorageSettings.ApplicationSettings.Add("lastBranoCalled", this.Panorama.SelectedIndex.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM