运算符“-”不能应用于字符串和字符串类型的操作数

时间:2019-02-27 18:57:04

标签: c# variables math operator-keyword

我想使用两个字符串变量创建一个新变量。但是我不断收到错误消息

  

“运算符'-'不能应用于字符串和字符串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;

“数量”为int类型
“ buypriceperbook”为双字型

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

转换为数字类型而不是字符串:

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

其他注意事项:

  • ExecuteScalar仅会给您查询中的 first 值-您的查询是否保证仅返回一个值?还是您希望某些东西可以汇总多个值?
  • ExecuteScalar返回一个object,表示它可以是字符串,双精度数,整数,空值等。如果强制转换为int,则表示 查询将返回非空整数值,否则它将在运行时失败。

答案 1 :(得分:0)

不能将算术运算符应用于字符串。更改为双精度或整数:

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;