alternatefaraz
alternatefaraz

Reputation: 374

ExecuteScalar: Connection property has not been initialized

I've tried lots of suggestions on the Internet in order to run executeScalar, but I get the error ExecuteScalar: Connection property has not been initialized. My INSERT query is working fine, the problem is with executeScalar.

conn.Open();
SqlCommand cmd = new SqlCommand(
    "INSERT INTO Products (Product_Name,Product_BarCode,Product_CP,Product_SP,
                           Product_Countainer,Product_Pcs,Product_MFGDate,
                           Product_ExpiryDate,Product_Grade)
     Values ('" + Name.Text + "','" + BarCode.Text + "','" + CostP.Value + "','" + 
             SellingP.Value + "','" + Countainer.Value + "','" + Pcs.Value + "','" + 
             MfgDate.Value + "','" + ExpDate.Value + "','" + Grade.SelectedItem + "')", 
     conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
cmd.Connection = conn;
cmd = new SqlCommand("SELECT SUM(Product_CP) FROM Products AS Amount");
Amount = (double)cmd.ExecuteScalar();
MessageBox.Show(Amount.ToString());
conn.Close();

Upvotes: 7

Views: 24494

Answers (3)

Mariusz Sz
Mariusz Sz

Reputation: 21

This cmd.Connection = conn;

should be after declaration

cmd = new SqlCommand("SELECT SUM(Product_CP) FROM Products AS Amount");
cmd.Connection = conn;

Upvotes: 0

Saruchi
Saruchi

Reputation: 366

In Case you are using DBCommand instead of SQLCommand, this won't be able to solve the problem as DBCommand is an Abstract class and can not be instantiated..

The solution that worked for me was : i was using command.executeScalar() where i had to use: DbCommand.executeScalar (command) // works wonders!

Upvotes: 0

SLaks
SLaks

Reputation: 887937

cmd = new SqlCommand(...);

As the error clearly states, this command doesn't have a connection.

Upvotes: 16

Related Questions