MangoTable
MangoTable

Reputation: 705

Help with using SQL select statement in C#

I am trying to retrieve some rows from the database using simple SELECT statement in SQL and displaying them in a Data Grid, Now what I have to do is to multiply the retrieved values with some factor and then display it. I am trying to achieve it the following way:

I have declared PerDoseSize1 as a double variable which gets its value from a function. I am not able to do it this way. It gives me an error saying "PerDoseSize1 is not a valid column"

  public void FillDG1(string Chemical_Name0, string Chemical_Name1, string Chemical_Name2, string Chemical_Name3,double PerDoseSize1)
{

  objDs.Clear();
  string connString ="Data Source=dk1;Integrated Security=True";
  SqlConnection con = new SqlConnection(connString);
  con.Open();
  SqlCommand cmd = new SqlCommand();
  cmd.Connection = con;
  cmd.CommandType = System.Data.CommandType.Text;
  cmd.CommandText = "SELECT [Chemical Name],([GWP])*(perdosesize) AS GlobalWarming, ([ODP])*(perdosesize) AS OzoneDepletion,  [WDP] AS WaterDepletion ,[FDP] AS FossilDepletion FROM [Surfactants$] WHERE ([Chemical Name] IN ( @ChemicalName0, @ChemicalName1,@ChemicalName2 ,@ChemicalName3)) ";
  cmd.Parameters.AddWithValue("@ChemicalName0",Chemical_Name0);
  cmd.Parameters.AddWithValue("@ChemicalName1", Chemical_Name1);
  cmd.Parameters.AddWithValue("@ChemicalName2", Chemical_Name2);
  cmd.Parameters.AddWithValue("@ChemicalName3", Chemical_Name3);
  cmd.Parameters.AddWithValue("@perdosesize", PerDoseSize1);
 SqlDataAdapter dAdapter = new SqlDataAdapter();
  dAdapter.SelectCommand = cmd;
  dAdapter.Fill(objDs);
 DataTable myDataTable = objDs.Tables[0];
 DG1.DataContext = objDs.Tables[0].DefaultView;     
  cmd.ExecuteNonQuery();
  MessageBox.Show(ChemicalName0,ChemicalName1);
  con.Close();
}

It still doesn't seem to work, Is it still wrong? Please help!

Upvotes: 0

Views: 972

Answers (2)

TomTom
TomTom

Reputation: 62093

I have declared PerDoseSize1 as a double variable which gets its value from a function

So what? How does that get into the SQL? So far there is NOTHING saying this. YOU have to put it into the SQL and assign it to a parameter. It wont magically hook up.

Upvotes: 0

E. Rodriguez
E. Rodriguez

Reputation: 717

The way you have written it:

"SELECT ([GWP])*(PerDoseSize1) AS GlobalWarming, ([ODP])*(PerDoseSize1) 

Will not work because the function argument you're passing in won't be substituted in your SQL.

So you can try creating a Parameter argument for PerDoseSize1 and pass it into the SQL, like you're doing with AddWithValue.

Upvotes: 2

Related Questions