OK I have created a product table [ID, itemCode], a sales table and a view that returns SUM of items in stock. Thing is if the item has not been sold yet, there is no record of it in the view. I need to check if item is in stock in order to complete further sales etc.
What I have done is this:
string selectSQL = "SELECT [total] FROM [stock] WHERE ([itemCode] = " + TextBoxCode.Text + ")";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(selectSQL, con);
try
{
con.Open();
object obj = com.ExecuteScalar();
if (obj == null) //(also tried is DBNull)
{
lblStatus.Text = "Does not exist in stock";
}
else
{
sum = com.ExecuteScalar().ToString();
lblStatus.Text = "Items in stock: " + sum;
}
}
catch (Exception err)
{
lblStatus.Text = err.Message;
}
finally
{
con.Close();
}
It works fine when the item actually exists in stock but if there is no record i get the error:
Conversion failed when converting the nvarchar value '1E001' to data type int.
'1E001' is the first itemCode in my stock view but it is irrelevant to the itemCode I am trying to insert.
The problem seems to be in the line:
object obj = com.ExecuteScalar();
I have also tried a
"SELECT COUNT(total) FROM [stock] WHERE ([itemCode] = " + TextBoxCode.Text + ")";
with the same results. I can't get it to work.
com.ExecuteScalar()twice, you also execute the query twice whileobjshould already contain the answer.