I am using an OdbcConnection
object to query data from my database and i get this Null Reference Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
This is my C# source code:
public void ValidateConnection(string connectionString)
{
// i verified the connection string, it works fine.
OdbcConnection connection = new OdbcConnection(connectionString);
OdbcCommand command;
OdbcDataReader reader;
int qresult;
try
{
connection.Open();
command = new OdbcCommand("select id, username, password from users where username=?", connection);
command.Parameters.Add("username", tb_username.Text);
try
{
reader = command.ExecuteReader();
if (reader.Read())
{
if (reader.GetString(2) == tb_password.Text)
{
// Found the correct password and username match.
reader.Close();
OdbcCommand command1 = new OdbcCommand("update users set username=?,password=? where username=?", connection);
command1.Parameters.Add( "password", tb_password.Text);
command.Parameters.Add("username", tb_username.Text);
qresult = command1.ExecuteNonQuery();
tb_username.Text = String.Empty;
tb_password.Text = String.Empty;
}
else
MessageBox.Show("ERROR: Password and Username do not match.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
MessageBox.Show("ERROR: Incorrect username and/or password!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("ERROR: Unknown error occured.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
connection.Close();
} catch (Exception ex) {
MessageBox.Show("ERROR: Cannot connect to system Database..", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The exception Occurs at line number #17 :
reader = command.ExecuteReader();
Please help?