You get this error because you don't use parameters.
string cmdStr = "SELECT COUNT(*) FROM Sale WHERE Date = @dt " +
"AND User = @usr " +
"AND Item = @itm " +
"AND Name = @name";
SqlCommand Pexist = new SqlCommand(cmdStr, myConnection3);
Pexist.Parameter.AddWithValue("@dt", DateTime.Today);
Pexist.Parameter.AddWithValue("@usr", UserBox.Text);
Pexist.Parameter.AddWithValue("@itm", ID505.Text);
Pexist.Parameter.AddWithValue("@name", DropDownList1.SelectedItem.ToString());
object result = Pexist.ExecuteScalar();
int P = (result == null ? 0 : Convert.ToInt32(result));
myConnection.Close();
When you use parameters, you let the database engine treat your input string. The database engine knows how to handle date, string and numbers. You are free from parsing problems and you avoid Sql Injection Attacks.
For example, what happen in your query string if the textbox ID505 contains a single quote?
Also, ExecuteScalar returns an object that is
The first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty
So it is better to check for null before trying to convert the result in an integer.
EDIT Looking back at this question after a while I should add that in this particular case the return from ExecuteScalar could never be null. This is the case because the query uses the aggregate function COUNT(*) that will return always a valid number also in case of no record found.