1
        QueryClass Query;
        string UserName = "";
        int UserId = 0;


        string email = txtEmail.Text;
        string name = txtUserName.Text;
        string phone = txtPhone.Text;
        byte[] buffer = new byte[100];

            UserName = Query.GetUserName(email); //returns a string value

            if (UserName != null)
            {
                MessageBox.Show(UserName + " is already in the database");
            }

            if (Query.AddNewUser(name, email, phone) == true) //returns a bool value
            {
                UserId = Query.GetUserId(email); //returns a int value
                if (Query.AddNewImage(UserId, buffer) == true) //returns a bool value
                {
                    MessageBox.Show("Done..!!");
                }

            }

            MessageBox.Show("Error");  

I'm getting the following error after I click the insert button (above code) of my program.

System.NullReferenceException
Message="Object reference not set to an instance of an object."

I'm getting that exception on following places. (i didn't check other places) code just stops these places and gives the error.

UserName = Query.GetUserName(email); //returns a string value

if (Query.AddNewUser(name, email, phone) == true) //returns a bool value

Can anyone please help me to fix this error? I'm using Visual studio 2010.

4

1 回答 1

9

You're using Query without actually setting it to anything. You likely need to construct an instance:

// Change: QueryClass Query;
QueryClass Query = new QueryClass();

Without creating an instance, when you call:

 UserName = Query.GetUserName(email);

At this point, Query is still the default value (which is null for a reference type), and you'll get a NullReferenceException upon trying to use it.

On a side note, you might want to consider naming this variable query (lower case), and the class Query (or, better yet, a more descriptive name), in order to follow the normal .NET naming guidelines.

于 2013-05-15T16:53:53.673 回答