thug_ thug_ - 1 month ago 16
C# Question

How I can access to specific item in the generic list

So I would like to make windows form in c#, which will have 2 textboxes one will be username, and other will be password... Also I will have a button LogIn.

When user press button LogIn, program will read through txt file, in which I have stored few usernames, they are stored like this (username, password, accNum, accBalance), so in the case that user enter correct username and password it should display in other form accNum and accBalance.

Until now I have this

private void btnLogIn_Click(object sender, EventArgs e)
{
List<User> users = new List<User>();
User currentuser = new User();

string str;
string[] strarray;
StreamReader sr = new StreamReader("path..");
while (sr.Peek() >= 0)
{
str = sr.ReadLine();
strarray = str.Split(',');
currentuser.username = strarray[0];
currentuser.password = strarray[1];
currentuser.accNumber = double.Parse(strarray[2]);
currentuser.accBalance = double.Parse(strarray[3]);
users.Add(currentuser);
}
}
}
public class User
{
public string username { get; set; }
public string password { get; set; }
public double accNumber { get; set; }
public double accBalance { get; set; }
}


When I try to output my users I am getting just last user, probably it is overwriting, position 0 in List, and I don't know how to avoid that...

Answer

You have to create the user object which you are adding to a List<User> for each User new. If you don't create a new User object for every specified User, you are just adding a reference to the same User to List<User> which results that every change you apply to one of the User objects stored in List<User> affects all other entries of the List<> because every entry is a reference to the same User object.

In your case this means you have to create a new User object in every iteration of the while loop:

List<User> users = new List<User>();
StreamReader sr = new StreamReader("path..");

while (sr.Peek() >= 0)
{
    var str = sr.ReadLine();
    var strarray = str.Split(',');

    var currentuser = new User();  //Creating a new user for every iteration
    currentuser.username = strarray[0];
    currentuser.password = strarray[1];
    currentuser.accNumber = double.Parse(strarray[2]);
    currentuser.accBalance = double.Parse(strarray[3]);
    users.Add(currentuser);
}
Comments