Reputation: 37
i have a program which a part of it includes registering a user and then login in with that username pass he provided when he registered every time we run the program. i know that this can be accomplished with a simple database but i want to use the project settings instead. i have a user class:
class User
{
public string name { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public User(string name, string username, string password, string email)
{
this.name = name;
this.username = username;
this.password = password;
this.email = email;
}
}
and then with the use of this post(from ismail-degani) in this page : Using Settings with Complex Types now i have created a list and this is the xml portion:
<Setting Name="Users" Type="System.Collections.Generic.List`1[Forum.User]" Scope="User">
<Value Profile="(Default)" />
</Setting>
now i can access this list and in the first i new it with this(i have a count which indicates is this the first run or not)
private void Login_Form_Load(object sender, EventArgs e)
{
if (Settings.Default.Count == 0)
{
Settings.Default.Users = new List<User>();
}
}
and after adding some user to it i count++ and save it with settings.default.save() function. but after running the program again my list becomes null again but the count is working just fine. what the problem may be?
Update: this is how i add a user and save the settings:
private void sabtuser()
{
User newuser = new User(tb_name.Text, tb_username.Text, tb_password.Text, tb_email.Text);
Settings.Default.Users.Add(newuser);
Settings.Default.Count++;
Settings.Default.Save();
this.Close();
}
Upvotes: 1
Views: 390
Reputation:
To save and reload your list of User
objects to and from the settings file, you will need to make the class public and provide a default (parameter-less) constructor. (The default constructor can be private.)
public class User
{
private User() {}
public string name { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public User(string name, string username, string password, string email)
{
this.name = name;
this.username = username;
this.password = password;
this.email = email;
}
}
Without the class being public, the data will not be written to the settings file.
Without the default parameter-less constructor, the data will not be read from the file again.
Upvotes: 1
Reputation: 4893
Most likely you need to change the scope of the setting to Application level instead of User level.
<Setting Name="Users" Type="System.Collections.Generic.List`1[Forum.User]" Scope="Application">
<Value Profile="(Default)" />
</Setting>
Upvotes: 1