0

I am trying to select and display the average temperature in my application from a chart. After the execution of my SQL command I expected to show the average temperature in my chart but it throws :

System.IndexOutOfRangeException:'Temperature'

This is the code that I have . I will be grateful if someone can help me .

    private void Database(string location, string temperature, string unit)
    {
        SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\MyPC\source\repos\NHLweatherStation\NHLweatherStation\Database1.mdf;Integrated Security=True");

        connection.Open();
        SqlCommand sqlCommand = new SqlCommand("INSERT INTO Weather (location,Temperature,date,unitsTemperature) VALUES ('" + location + "','" + temperature + "','" + DateTime.Now + "','" + unit + "')", connection);


        sqlCommand.ExecuteNonQuery();


        connection.Close();

        SqlCommand cmd = new SqlCommand("Select avg(Temperature),date From Weather Group by date", connection);
        connection.Open();

        SqlDataReader rdr = cmd.ExecuteReader();
        TrendGraph.Series["Series1"].XValueMember = "date";
        TrendGraph.Series["Series1"].YValueMembers = "Temperature";
        TrendGraph.DataSource = rdr;
        TrendGraph.DataBind();

        connection.Close();

    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    `Select avg(Temperature) as Temperature` – Chetan Jun 13 '20 at 12:04
  • @ChetanRanpariya thank you . That is a dumb mistake . – georgi dimitrov Jun 13 '20 at 12:05
  • 2
    You aren't selecting a column named Temperature, but the average of it. You need to use an `as` like indicated above to give it a name so you can reference it. Unrelated to the question, you should also look into using parameterised queries to insert data (unless the insert code is temporary for debugging) as as it is written is vulnerable to SQL Injection. – Martin Costello Jun 13 '20 at 12:06
  • @MartinCostello Yes ! Will look into it . – georgi dimitrov Jun 13 '20 at 12:12
  • Please also read https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection . – mjwills Jun 13 '20 at 12:57

0 Answers0