Reputation: 2965
I am attempting to store a userID in my config file which I then want to access throughout my program for numerous reasons. I have the appSettings
section in the config file like so;
<appSettings>
<add key="userID" value="1" />
</appSettings>
I then set the value in one method;
private void hrButton_Click(object sender, RoutedEventArgs e)
{
DataAccessor da = new DataAccessor();
DataRowView dataRow = (DataRowView)dataGrid.SelectedItem;
// Open App.Config of executable
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Add("userID", dataRow.Row.ItemArray[0].ToString());
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
da.SetUserDetails();
NavigationService.Navigate(new Uri(@"View/HRSystem/HRSystem.xaml", UriKind.Relative));
}
Before attempting to access and use it in another;
public List<string> SetUserDetails()
{
string userID = ConfigurationManager.AppSettings.Get("userID");
MessageBox.Show("userID: "+userID);
string constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString;
using (OleDbConnection dbfCon = new OleDbConnection(constr))
{
try
{
dbfCon.Open();
OleDbDataReader myReader;
OleDbCommand sqlCmd = new OleDbCommand("SELECT em_pplid FROM employs WHERE em_pplid = "+ userID + "", dbfCon);
myReader = sqlCmd.ExecuteReader();
List<string> listUser = new List<string>();
while (myReader.Read())
{
listUser.Add(myReader[0].ToString());
return listUser;
}
}
catch (MySqlException)
{
throw;
}
}
return null;
}
However when I show the userID
in the message box it is still set to 1. I haven't used the appSettings
section before, is there a reason why it is always 1? I'm running Visual Studio 2015, C# WPF.
Upvotes: 2
Views: 1577
Reputation: 332
Add config.AppSettings.Settings.Remove("userID");
on the line just above config.AppSettings.Settings.Add();
But the correct way to save such information is to use a Settings File
Set:
Properties.Settings.Default.userID = dataRow.Row.ItemArray[0].ToString();
Properties.Settings.Default.Save();
Retreive:
var userId = Properties.Settings.Default.userID;
Upvotes: 2
Reputation: 49
try
config.AppSettings.Settings.Remove('userID');
config.AppSettings.Settings.Add('userID', dataRow.Row.ItemArray[0].ToString());
But you should not store the user id in the configuration file. You should save it in session or Cookie
Upvotes: 0