【问题标题】:Passing DropDownList value into SQL command in ASP.net将 DropDownList 值传递给 ASP.net 中的 SQL 命令
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    //查询=Sql查询

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

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2016-06-07
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2016-02-27
      相关资源
      最近更新 更多