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

问题描述

我有一个DropDownList,它可以从sql表中获取
我想从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
我相信问题在于DropDownlist值,这些值是从sql接收到的,不是硬编码的。
有正确的方法吗?是否可能不知道高级“ Courses”是什么?

感谢您的回答,随时发表您的看法。

解决方法

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

,

//查询= Sql查询

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