I have a Login validation problem, when

Username = 123-incorrect
Password = 123-incorrect
Login Failed.

when
Username = onat12-correct
Password = sambuca888-correct
Login Accepted.

now when,
Username = onat12-correct
Password = 123-incorrect
Login Failed.


now when,
Username = 123-incorrect
Password = 123-incorrect
Will not validate
Verification failed

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;


namespace Form_Login1
{
    public partial class frm_login : Form
    {
        public frm_login()
        {
            InitializeComponent();

        }
        int usercode;
        System.Data.OleDb.OleDbConnection con;
        private void frm_login_Load(object sender, EventArgs e)
        {//verify database is running
            try
            {
                con = new System.Data.OleDb.OleDbConnection();
                con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=dbSys.mdb;User Id=admin;Password=;";
                con.Open();


                MessageBox.Show("Connection Verified, Cleared to login", "O-Connection Has Been Verified-O",
                MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation);
                con.Close();
                con.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "X-Database Error-X",
                   MessageBoxButtons.OK,
                   MessageBoxIcon.Exclamation);
                this.Close();

            }

            //end database verification
        }

        private void btn_try_Click(object sender, EventArgs e)
        {//login
            using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=dbSys.mdb;User Id=admin;Password=;"))
            {
                using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM users WHERE UserName=@UserName AND PassWord_=@PassWord_", cn))
                {
                    cmd.Parameters.Add("@UserName", OleDbType.WChar, 50, "UserName").Value = this.tbx_user.Text;

                    cmd.Parameters.Add("@Password", OleDbType.WChar, 50, "PassWord").Value = this.tbx_pwd.Text;

                    if (cn.State == ConnectionState.Closed)
                    {
                        cn.Open();

                        using (OleDbDataReader rdr = cmd.ExecuteReader())
                        {
                            if (rdr.HasRows)
                            {
                                rdr.Read();

                                if ((rdr.GetString(1) == this.tbx_user.Text) && (rdr.GetString(2) == this.tbx_pwd.Text))
                                {
                                    MessageBox.Show("Login Succesful");
                                    con.Close();
                                    con.Dispose();
                                    usercode = 
                                    MainPage f = new MainPage(usercode);
                                    f.Show();
                                    this.Close();
                                    ;


                                }
                                else
                                {

                                    MessageBox.Show("Verification Failed");
                                    tbx_pwd.Text = "";
                                    tbx_user.Text = "";
                                }
                            }

                        }
                    }
                }
            }

        }

        private void btn_abrt_Click(object sender, EventArgs e)
        {//close
            con.Close();
            con.Dispose();
            this.Close();
        }







    }
}

Dani AI

Generated

Brief diagnosis and a short, practical correction.

The symptoms described by (alphanumeric logins succeed, numeric-only entries behave inconsistently or produce "Verification failed") point to parameter/typing and connection-management problems rather than the final string comparison. Two quick, common causes to check: 1) parameter binding mismatches when using OleDb, and 2) fragile column access by ordinal (rdr.GetString(index)) which will fail or mis-cast when the database column type is not text.

Concrete items to fix (found gaps in the posted code and in ' note about the connection state):

  • Parameter names vs query: the SQL uses a different token than the parameter added. With the Jet/OleDb provider named parameters are ignored and parameters are positional — either use question-mark placeholders (?) and add parameters in the same order, or make sure the command text and Add/Value calls line up exactly.
  • Parameter overload: using the Add overload that takes a source-column string can be misleading. Prefer creating parameters and setting Value, or AddWithValue, so the Value is explicit.
  • Connection confusion: con (a field) is opened/disposed in Load while cn (local) is used in click code — do not call con.Close()/Dispose() when using cn. Also avoid relying on if (cn.State == ConnectionState.Closed) — either open unconditionally or check != ConnectionState.Open so code doesn't silently skip execution. (This is the point raised.)
  • Reader access: avoid GetString(i) by index. Use rdr["UserName"].ToString() or GetOrdinal + IsDBNull checks so numeric or null fields don't throw or mis-compare. Also the SQL WHERE already ensures a match; re-checking the fields is redundant.

A compact, safer pattern (illustrative) — parameter order matters with OleDb:

using (var cn = new OleDbConnection(connString))
using (var cmd = new OleDbCommand("SELECT UserId FROM users WHERE UserName = ? AND PassWord_ = ?", cn))
{
  cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar, Value = tbx_user.Text });
  cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar, Value = tbx_pwd.Text });
  cn.Open();
  var id = cmd.ExecuteScalar();
  // id != null => valid user; assign to usercode and continue
}

Additional recommendations: log exceptions so failures are visible, confirm DB column types (text vs numeric), never store plaintext passwords (use salted hashes), and keep connection lifetime local and predictable. These changes address the mismatched-parameter and connection-state issues that cause the inconsistent validation seen in this thread.

In your code you have this line:

if (cn.State == ConnectionState.Closed)

but I can't see a section where you continue if the cn.State is open. Depending on whether you handled any other opening/closing of that connection you may have a problem (the two functions here look OK but you may have other code that leaves the connection open elsewhere).

Also, you are selecting all from the database where user name and password matches but then, when checking if the data reader has rows you are running the same check again:

if ((rdr.GetString(1) == this.tbx_user.Text) && (rdr.GetString(2) == this.tbx_pwd.Text))

This seems unnecessary as the reader can only contain rows if the user name/password have already been matched.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.