简体   繁体   中英

Comparing Database values with an input value?

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;
    }
}

http://i.imgur.com/5DF4Mj6.png Showing the Error when program is ran

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});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM