0

I am checking username from DB table when a user enters username in registration page an textbox OnTextChanged event fired which checks if username is already exists or not. Here is code :

public void HandleTextbox1OnTextChanged(Object sender, EventArgs e)
{
    string _connString = ConfigurationManager.AppSettings["connString"];
    string username = txtUserName.Text;
    int result = 0;
    using (SqlConnection conn = new SqlConnection(_connString))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from  ref_CourseRegistration_Users where nm_UserName=@nm_UserName", conn);
        cmd.Parameters.AddWithValue("@nm_UserName", username);
        cmd.ExecuteNonQuery();
        result = (int)cmd.ExecuteScalar();
        if (result > 0)
        {
            lblMessage.Text = "username already exists, please enter different User Name!";
            lblMessage.ForeColor = Color.Red;
        }
        else
        {

        }
    }
}

it works fine when username exists but when username doesn't exists it shows an error "Object reference not set to an instance of an object." if i am missing anything?

1
  • Always point out the line where the exception is occurring. Commented Apr 28, 2014 at 7:22

1 Answer 1

3

You expect the number of users with the same name from your query, so you should select it:

Remove the line cmd.ExecuteNonQuery(); from your code, you already use cmd.ExecuteScalar(); and that's fine.

Your select should return a number, so you should select a number:

select COUNT(*) from  ref_CourseRegistration_Users where nm_UserName=@nm_UserName

If you don't do this, you will get null from your query and that results in a null reference exception on your end because you don't handle it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.