sachintha imindhu
sachintha imindhu

Reputation: 21

Operator '-' cannot be applied to operands of type string and string

I want to create a new variable using two string variables. But I keep getting the error message

"operator '-' cannot be applied to operands of type string and string c#".

string query3 = "SELECT Quantity FROM Supplier WHERE [Supplier ID]='"+supplierid+"'";
string query4 = "SELECT Quantity FROM Supplier WHERE [Book ID] = '" + bookid + "'";
SqlCommand cmd3 = new SqlCommand(query3, con);
SqlCommand cmd4 = new SqlCommand(query4, con);
con.Open();
string temporaryquantity = cmd3.ExecuteScalar().ToString();
string temporaryquantitystocks = cmd4.ExecuteScalar().ToString();
string totalcostforstocks = (temporaryquantitystocks-temporaryquantity + quantity) * buyingpriceperbook;

"quantity" is in int type
"buyingpriceperbook" is in double type

Can anyone help me with this?

Upvotes: 1

Views: 2495

Answers (2)

Sérgio Sereno
Sérgio Sereno

Reputation: 149

You can not apply arithmetic operators to strings. Change to double or integer:

string query3 = "SELECT Quantity FROM Supplier WHERE [Supplier ID]='" + supplierid + "'";
string query4 = "SELECT Quantity FROM Supplier WHERE [Book ID] = '" + bookid + "'";

SqlCommand cmd3 = new SqlCommand(query3, con);
SqlCommand cmd4 = new SqlCommand(query4, con);
con.Open();
double temporaryquantity = Convert.ToDouble( cmd3.ExecuteScalar());
double temporaryquantitystocks = Convert.ToDouble(cmd4.ExecuteScalar());
double totalcostforstocks = (temporaryquantitystocks - temporaryquantity + quantity) * buyingpriceperbook;

Upvotes: 0

D Stanley
D Stanley

Reputation: 152644

Convert to a numeric type rather than strings:

int temporaryquantity = (int)cmd3.ExecuteScalar();

Other things to note:

  • ExecuteScalar will give you only the first value from your query - are your queries guaranteed to only return one value? Or are you expecting something to sum up multiple values?
  • ExecuteScalar returns an object, meaning it can be a string, a double, an integer, null, etc. If you cast to int you are assuming that the query is returning a non-null integer value, otherwise it will fail at runtime.

Upvotes: 0

Related Questions