【发布时间】:2020-10-26 18:26:51
【问题描述】:
我有一个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”是什么的情况下是否有可能?
感谢您的回答,请随时发表您的意见。
【问题讨论】:
-
我认为 DropDownList1.SelectedItem 将是一个对象。使用 .ToString()...
-
DropDownList1.SelectedValue -
之前尝试了所有这些,但没有任何效果。
标签: sql asp.net drop-down-menu html-select selectedvalue