0

When I enter incorrect username and password it does not go to error.aspx(form). this is my code:

protected void Button1_Click(object sender, EventArgs e)
{

    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    conn.Open();
    string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
    SqlCommand com = new SqlCommand(checkuser,conn);
    int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
    conn.Close();

    if (temp == 1)
    {
        conn.Open();
        string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
        SqlCommand passComm = new SqlCommand(checkpassword, conn);
        string password = passComm.ExecuteScalar().ToString();
        if (password == TextBoxPassword.Text)
        {
            //Session["NEW"] = TextBoxUserName.Text;
            Response.Redirect("Welcome.aspx");
        }
        **else
          if (password != TextBoxPassword.Text)
          {
              Response.Redirect("Error.aspx");
          }**
  }

It gives me an error saying "Object reference not set to an instance of an object" in this line of code: string password = passComm.ExecuteScalar().ToString();

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • 4
    1. Read about SQL Injection and how to prevent it. 2. You're missing an `=` sign between the column and the value in your WHERE clause (i.e., `WHERE Username = '" + value + "'"`) – Tim Oct 15 '14 at 04:21
  • 1
    @Alex Bazikalo Use `Response.Redirect("~/Error.aspx");` – Thirisangu Ramanathan Oct 15 '14 at 04:24
  • only Response.Redirect("~/Error.aspx")? – Alex Bazikalo Oct 15 '14 at 04:25
  • 1
    @AlexBazikalo Yes and make sure the `WHERE Username=...` – Thirisangu Ramanathan Oct 15 '14 at 04:27
  • @Thirisangu - That will only work if the page being redirected to is in the root of the site. – Tim Oct 15 '14 at 04:28
  • @AlexBazikalo - Also, why are you checking the count of Username? The user name should be unique, or the user name and password should be unique. – Tim Oct 15 '14 at 04:32
  • @AlexBazikalo - Did you not study the answers to your [previous question](http://stackoverflow.com/q/26366149/745969)? It appears you're making similar mistakes to your first question. – Tim Oct 15 '14 at 04:42
  • 1
    Never, and I really mean never, store your passwords in plain text. You're using ASP.net, you look like you are new to this, let asp.net handle users for you with: http://msdn.microsoft.com/en-us/library/vstudio/yh26yfzy%28v=vs.100%29.aspx – Jon P Oct 15 '14 at 04:51

0 Answers0