Click here to Skip to main content
15,908,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i m making a textbox with a button so that when button is clicked it gives sum of specified column in that textbox it has to be done in c#.plz help
C#
MySqlConnection MyCon = new MySqlConnection("server=localhost; Database = nikz; user id=root; password=***; pooling=false;");
MyCon.Open();
MySqlCommand command = new MySqlCommand();
string SQL = "select sum(Actual_amt) from tds";
command.Connection = MyCon;
command.CommandText = SQL;
actamttxtbox.Text = SQL.ExecuteScalar();
command.ExecuteNonQuery();
MyCon.Close();

this is what i hav done and is giving errors
Posted
Updated 17-Jul-12 1:10am
v2
Comments
AmitGajjar 17-Jul-12 7:08am    
Whats your problem ? what is your error ?

1 solution

variable SQL is a string. A string has no method ExecuteScalar()

change
C#
actamttxtbox.Text = SQL.ExecuteScalar();

to
C#
actamttxtbox.Text = (string)command.ExecuteScalar();

And you don't need cmd.ExecuteNonQuery();



I've cleaned up a little bit:

C#
MySqlConnection conn = new MySqlConnection("connection-string");
conn.Open();

using(MySqlCommand cmd = new MySqlCommand()){
  cmd.Connection = conn;
  cmd.CommandText = "select sum(Actual_amt) from tds";
  actamttxtbox.Text = cmd.ExecuteScalar().ToString();
}
conn.Close();
 
Share this answer
 
v6
Comments
nkhldhar 17-Jul-12 7:16am    
Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
nkhldhar 17-Jul-12 7:17am    
edited but having this error
StianSandberg 17-Jul-12 7:17am    
You are correct! Fixed it in my last edit :)
nkhldhar 17-Jul-12 7:21am    
now this error pops up
The name 'MyCon' does not exist in the current context
StianSandberg 17-Jul-12 7:23am    
ops.. sorry. a typo.. fixed it now. Changed your variable name and forgot to update cmd.Connection = conn;.. my bad..

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