运算符' - '不能应用于'string'和'int'类型的操作数 [英] Operator '-' cannot be applied to operands of type 'string' and 'int'

查看:191
本文介绍了运算符' - '不能应用于'string'和'int'类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的



i有网格视图,有2个INT值的字段,我想在它们之间做' - '运算符,



i做这样的事情:



Dear

i have grid view and there is 2 fields with INT value, i want to made '-' operator between them,

i do something like this :

SqlCommand com2 = new SqlCommand("update Book SET (Total) ='" + Convert.ToInt32(g1.Cells[5].Text) - Convert.ToInt32(g1.Cells[4].Text) + "')", con);





当我运行页面时出现此错误:



运算符' - '不能应用于类型的操作数' string'和'int'。



DB中的两个字段都是INT。





* G1是gridview名称



when i run the page i got this error:

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

both field in DB is INT.


* G1 is gridview name

推荐答案

试试这个 -

Try this -
string st = string.Format("update Book SET (Total) ='{0}')", (Convert.ToInt32(g1.Cells[5].Text) - Convert.ToInt32(g1.Cells[4].Text))); 
SqlCommand com2 = new SqlCommand(st, con);


在计算周围加上一个括号,以便正确计算内部值,然后转换为用于连接的字符串:

Put a parenthesis around your computation so the inner value is evaluated correctly then converted to a string for concatenation :
SqlCommand com2 = new SqlCommand("update Book SET (Total) =" + ( Convert.ToInt32(g1.Cells[5].Text) - Convert.ToInt32(g1.Cells[4].Text) ) , con);


你尝试连接字符串和int但是没有设置优先级...

你要做的是:

You try to concatenate string and int but do not set precedence...
What you try to do is:
"string" + int - int + "string"



问题是在strin之后g+ int part你会得到一个字符串,所以接下来的计算是string - int,这是不可能完成的!

请记住,+和 - 之间没有优先权!

您可以使用括号来解决它,但我建议您了解String.Format以及C#中的参数化SQL命令(最重要的!!!)


The problem is that after the "string" + int part you will get a string, so the next computation is "string" - int, and that can not be done!
Remember that there is no precedence between + and -!!!
You can use parenthesis to solve it, but I advise you to learn about String.Format and about parametrized SQL commands in C# (most important!!!)


这篇关于运算符' - '不能应用于'string'和'int'类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆