将 DropDownList 值传递到 ASP.net 中的 SQL 命令

Passing DropDownList value into SQL command in ASP.net

我有一个 DropDownList 从 SQL table
获取值 我想从 dropDownList 中获取所选项目(在本例中为课程)的平均值,并将其显示在标签中:
本节作品-

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();

    }
}

这是问题所在 -(我什么也没得到,没有数据)

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
        }
   }

编辑
我尝试了几种变体,如 $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = @course"Command.Parameters.AddWithValue("@course", DropDownList1.SelectedItem.Text)
DropDownList1.SelectedValue
我认为问题出在从 SQL 接收到的 DropDownlist 值,并且没有硬编码。
有正确的方法吗?有没有可能不知道高级的“Courses”是什么?

感谢您的回答,欢迎发表您的意见。

我发现 aspx 页面(不是 aspx.cs 页面)中的 DropDownList 缺少了什么 - AutoPostBack="true"
将其添加到 DropDownList 解决了问题。

//查询=Sql查询

query.Select(s => new MusteriNoktaComboItemDTO
            {
                Label = s.Adi,
                Value = s.ID.ToString()
            }).ToList();