CH A ND
CH A ND

Reputation: 13

Why do I get "Object reference not set to an instance of an object" trying to connect to a database?

This code gives me following error in visual studio 2012

SqlConnection conn = new SqlConnection(
  ConfigurationManager.ConnectionString["erpConnStr"].ConnectionString);
conn.Open();

String validateUserQry = "SELECT * FROM members WHERE username = '" + username.Text + "'";
SqlCommand validateUserComm = new SqlCommand(validateUserQry, conn);
validateUserComm.ExecuteNonQuery();

if (validateUserComm.ExecuteScalar().ToString() == null)
{
   errorMsg.Visible = true;
   msg.Text = "Username was not Correct ! ";
}

The error is:

Object reference not set to an instance of an object.

I can tell that the error happens at this line:

if (validateUserComm.ExecuteScalar().ToString() == null) 

Why?

Upvotes: 0

Views: 959

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33511

Lose the ToString():

if (validateUserComm.ExecuteScalar() == null)

Upvotes: 3

Related Questions