given key was not present in the dictionary
c#
Solution
when you call `SiteSettings.GetSettingKeyValuePair()["LA_MembershipProvider_lostPasswordEmailFrom"])` if there is no key named `LA_MembershipProvider_lostPasswordEmailFrom` you will get "The given key was not present in the dictionary" error. What you can do is, check the whether key exist first and then get the value. You can do as below
public static string LostPasswordEmailFrom
{
get
{
var kvp = SiteSettings.GetSettingKeyValuePair();
if (kvp == null || !kvp.ContainsKey("LA_MembershipProvider_lostPasswordEmailFrom"))
return Globals.Settings.FromEmail;
return kvp["LA_MembershipProvider_lostPasswordEmailFrom"];
}
}
Problem
I inherited a project that gives users the above error while trying to retrieve lost password in a .Net 4.0 project. I stepped through and found the trouble spot, but the problem is, the values generated seem right so I don't why the error is occurring. Thanks in advance to anyone who can look at the following code and help me find out how to fix it. Let me know if more information is needed. I looked through everything I could find but nothing gave me clues I could use. Problem is that I just can't trace where the key/value combination should enter, nor would I know how to add it once I did. Code follows. I posted a similar discussion at http://forums.asp.net/t/1926444.aspx/1?given+key+was+not+present+in+the+dictionary but no one there knew how to help me. ``` void EmailUser(User user) { user.ChangePasswordID = Guid.NewGuid(); user.Save(); MailMessage email = new MailMessage(); //problem line below email.From = new MailAddress(Settings.LostPasswordEmailFrom); email.To.Add(new MailAddress(uxEmail.Text)); email.Subject = Settings.LostPasswordSubject; email.Body = EmailTemplateService.HtmlMessageBody(EmailTemplates.MembershipPasswordRecovery, new { Body = Settings.LostPasswordText, BeginRequired = "", EndRequired = "", UserName = user.Name, GUID = user.ChangePasswordID.ToString() }); email.IsBodyHtml = true; SmtpClient client = new SmtpClient(); client.Send(email); uxSuccessPH.Visible = true; uxQuestionPanel.Visible = false; uxUserInfoPanel.Visible = false; uxUserNameLabelSuccess.Text = uxEmail.Text; } /// <summary> /// The address that the lost password email will be sent from /// </summary> public static string LostPasswordEmailFrom { get { if (String.IsNullOrEmpty(SiteSettings.GetSettingKeyValuePair()["LA_MembershipProvider_lostPasswordEmailFrom"])) return Globals.Settings.FromEmail; return SiteSettings.GetSettingKeyValuePair()["LA_MembershipProvider_lostPasswordEmailFrom"]; } } ```