0

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

8
  • What does it not do? Commented Dec 19, 2014 at 13:07
  • Although, it looks as though you're missing a loop, as you're only going to be checking the first "Managers" record with that code. Possibly something like: foreach(Managers m in manager) { // do your check here } Commented Dec 19, 2014 at 13:09
  • It simply does not search the managers database for any login with the same username. I will attempt a loop just now. Commented Dec 19, 2014 at 13:11
  • You say "Managers is my database". Are you sure? On the face of it, it looks like a simple class that represents a manager. Commented Dec 19, 2014 at 13:19
  • My database is called 'ManagersDbContext'. I just realised my flaw. Thank you for the help. Commented Dec 19, 2014 at 13:24

1 Answer 1

2

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});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.