Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 :

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


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
Posted
Updated 20-Sep-14 22:28pm
v2

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);
 
Share this answer
 
Comments
firas_rehawi 21-Sep-14 7:36am    
Thanks But we i complete my statement i got error:
the complete statement is:

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

com2.ExecuteNonQuery();

and the error is: incorrect syntax near '('. "referring to the ExecuteNonQuery call"
Mehdi Gholam 21-Sep-14 8:43am    
5'ed, but the ending paran is extra.
Abhinav S 21-Sep-14 23:09pm    
Thanks.
Put a parenthesis around your computation so the inner value is evaluated correctly then converted to a string for concatenation :
C#
SqlCommand com2 = new SqlCommand("update Book SET (Total) =" + ( Convert.ToInt32(g1.Cells[5].Text) - Convert.ToInt32(g1.Cells[4].Text) ) , con);
 
Share this answer
 
v3
Comments
firas_rehawi 21-Sep-14 7:39am    
Thanks But we i complete my statement i got error:
the complete statement is:

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

com2.ExecuteNonQuery();

and the error is: incorrect syntax near '('. "referring to the ExecuteNonQuery call"
Mehdi Gholam 21-Sep-14 8:40am    
Try the edited version, removed the ending "')" which is not needed.
You try to concatenate string and int but do not set precedence...
What you try to do is:
C#
"string" + int - int + "string"

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!!!)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900