strollingchimp
strollingchimp

Reputation: 11

Value sets properly but is null when used

Ok, I have been able to retrieve a value from one class, Login, and have been able to store it in a public variable, userID, in another class, Main. I know that the value has been set properly as it is populating a label on the main window of my application which is using Main as its class. The value is also used to poll a database every second, however, this only works if I use an unparametrised SQL query. If I try to use a parametrised query I start seeing problems where the query is seeing the value as being null.

This query works, which is bad:

SqlCommand cmd_getMessage = new SqlCommand("SELECT message, sender_ID, date_time FROM Message WHERE recipient_ID='" + userID + "'", SQL);

Whereas this doesn't:

SqlCommand cmd_getMessage = new SqlCommand("SELECT message, sender_id, date_time FROM Message WHERE recipient_id=@recipient_id", SQL);
cmd_getMessage.Parameters.AddWithValue("@recipient_id", userID);

It is worth noting that these queries are in the same class as the public variable. If I try to access the variable from another class and then use it in an SQL query then even the unparametrised query will not work

Hopefully that is enough information for you to work with. Thanks for your time.

Upvotes: 1

Views: 83

Answers (1)

mh__
mh__

Reputation: 376

My guess is that userID at some point is null.

Try changing the parameter line to:

cmd_getMessage.Parameters.AddWithValue("@recipient_id", userID ?? "");

and see if you still get the error. That will make the two queries perform equally.

Upvotes: 4

Related Questions