Anicho
Anicho

Reputation: 2667

Comparing textbox.text value to value in SQL Server

Okay so I am trying to compare a login textbox password and username with a custom validator using linq to get information from the database it always returns false though on the validator could someone please tell me where my code below is going wrong. This will be very much appreciated... thank you in advanced...

protected void LoginValidate(object source, ServerValidateEventArgs args)
{
    TiamoDataContext context = new TiamoDataContext();

    var UsernameCheck = from User in context.Users
                      where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
                      select User.Username;

    var PasswordCheck = from User in context.Users
                    where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
                    select User.Password;

    String test1 = PasswordCheck.ToString();
    String test2 = UsernameCheck.ToString();

    if (test1 == TextBoxLogInPassword.Text && test2 == TextBoxLoginUsername.Text)
    {
        args.IsValid = true;
        Session["Username"] = TextBoxLoginUsername;
        Response.Redirect("UserProfile.aspx");

    }
    else 
    {
        args.IsValid = false;
    }

}

I dont know where I am going wrong I know its most probably some sort of silly mistake and me being inexperienced at this...

Upvotes: 2

Views: 2275

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245399

UsernameCheck and PasswordCheck are going to be collections, not single values. Therefore the ToString() method isn't returning what you think it should.

It's probably returning "IEnumerable<string>"

You need to force your LINQ queries to return a single result rather than a collection.

var user = context.Users.Where(u => u.Username==TextBoxLoginUsername.Text && 
                                    u.Password == TextBoxLogInPassword.Text)
               .FirstOrDefault();

string userNameCheck = user.Username;
string passwordCheck = user.Password;

As a side note, this is why using the var keyword is a little dangerous if you're not absolutely positive of the return type of the statement you're writing. If you would change your vars to strings, the compiler would have caught the type mismatch at compile time.

Upvotes: 2

Related Questions