Search code examples
sqlasp.netdrop-down-menuhtml-selectselectedvalue

Passing DropDownList value into SQL command in ASP.net


I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -

SqlConnection sqlConnection1;
    sqlConnection1 = new SqlConnection(@"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
    SqlCommand Command = null;
  
        Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
        Command.Connection.Open();
        SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
        DataTable dataTble1 = new DataTable();
        dataAdapter.Fill(dataTble1);

        if (dataTble1.Rows.Count > 0)
        {
            foreach (DataRow row in dataTble1.Rows)
            {
                ListItem course1 = new ListItem(row["Course"].ToString());
                if (!DropDownList1.Items.Contains(course1))
                {
                    DropDownList1.Items.Add(course1); // showing the 2 courses
                }
            }
        }
        Command.Connection.Close();

    }
}

Here is the problem - (I get nothing, no data )

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection sqlConnection1;
    sqlConnection1 = new SqlConnection(@"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
    SqlCommand Command = null;
  
        Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = @course", sqlConnection1);
        Command.Parameters.AddWithValue("@course", DropDownList1.SelectedItem);
        Command.Connection.Open();
        SqlDataReader sqlDataReader1 = Command.ExecuteReader();

        if (sqlDataReader1.Read())
        {
            LabelAverage.Text = sqlDataReader1[0].ToString();
        }
        else
        {
            LabelAverage.Text = "No Data"; // doesn't get into here anyhow
        }
   }

EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = @course" and Command.Parameters.AddWithValue("@course", DropDownList1.SelectedItem.Text),
or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?

Thanks for the answers, feel free to give your opinion.


Solution

  • I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
    Adding that to DropDownList solved the problem.