Reputation: 51
I'm attempting to create a register page for users to use. However, this allows users to have the same Username, in which I don't want to happen. I've wrote a piece of code, which I assumed would work but failed miserably.
Managers manager = new Managers();
//Compares to database to find any duplicate usernames
if (manager.Username == txtUsername.Text)
{
lblUsername.Text = "Please enter a different username!";
lblUsername.Visible = true;
}
Only gave the relevant part.
I was wondering if someone could explain to me what I have done wrong about this? Managers
is my database.
Edit- I added in a foreach loop, however was still accepted values.
List<Managers> manage = new List<Managers>();
Managers manager = new Managers();
foreach (Managers m in manage)
{
if (manager.Username == txtUsername.Text)
{
lblUsername.Text = "Please enter a different username!";
lblUsername.Visible = true;
}
}
https://i.sstatic.net/pxpGI.png Showing the Error when program is ran
Upvotes: 0
Views: 1968
Reputation: 557
Do something like :
var query = (from c in db.Users where c.UserName== userName select c);
if (query.Count() > 0)
{
// Message : user is exist
}
else
{
// register user
}
Edit :
Use lambda expressions
if (Manager.Users.Select(d => d).Where(d => d.UserName == UserName).ToList().Count() > 0)
{
// the Item is Exist in the list
}
else
{
Manager.Users.Add(new Users { UserName = Username, Pass= Password});
}
Upvotes: 2