在ASP.net中动态填充下拉列表,并将该值传递给另一个查询?

时间:2012-05-08 19:36:08

标签: asp.net drop-down-menu data-driven population

每个人都有2个问题。

1)我如何按价值订购年份,当我使用DESC时崩溃?

2)如果我像这样填写我的列表:

 string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
    SqlConnection con = new SqlConnection(strConn);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?

    DataSet objDs = new DataSet();
    SqlDataAdapter dAdapter = new SqlDataAdapter();
    dAdapter.SelectCommand = cmd;
    con.Open();
    dAdapter.Fill(objDs);
    con.Close();

    if (objDs.Tables[0].Rows.Count > 0)
    {
        ddItems.DataSource = objDs.Tables[0];
        ddItems.DataTextField = "Year";
        ddItems.DataValueField = "Year";
        ddItems.DataBind();
        ddItems.Items.Insert(0, "Select");
    }

如何使选定的年份显示在ddItems.SelectedItem?

WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";

当我动态填充列表时,另一个查询的那部分不起作用,任何理由为什么/如何解决它。

问候。

编辑: 为了使我的第二个问题更清楚,在调试之后总是选择下拉列表中的顶部项目而不是实际选择的项目?

4 个答案:

答案 0 :(得分:1)

并且1)

cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"

答案 1 :(得分:1)

首先,在您的SQL中,您缺少“order by”...使用此

"Select Distinct Year from MonthlySales order by Year DESC"

其次,您需要使用SelectedValue属性来获取下拉列表的选定值...如下所示......

WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";

话虽如此,我强烈建议您使用...“参数化”sql ...以下是如何启用参数化sql查询的示例... Give me parameterized SQL, or give me death

<强>更新

看起来你在每个帖子上绑定你的下拉列表......你可以试试这个......

if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
    {
        ddItems.DataSource = objDs.Tables[0];
        ddItems.DataTextField = "Year";
        ddItems.DataValueField = "Year";
        ddItems.DataBind();
        ddItems.Items.Insert(0, "Select");
    }

答案 2 :(得分:1)

您缺少order by。在这里。

"Select Distinct Year from MonthlySales order by Year DESC";

对于你的第二部分,你可以这样做。请注意" GROUP BY Name"

中的空格
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";

答案 3 :(得分:1)

using (SqlConnection con = new SqlConnection(strConn))
{
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";

        using (DataSet objDs = new DataSet())
        {
            using (SqlDataAdapter dAdapter = new SqlDataAdapter())
            {
                dAdapter.SelectCommand = cmd;
                con.Open();
                dAdapter.Fill(objDs);
                con.Close();

                if (objDs.Tables[0].Rows.Count > 0)
                {
                    ddItems.DataSource = objDs.Tables[0];
                    ddItems.DataTextField = "Year";
                    ddItems.DataValueField = "Year";
                    ddItems.DataBind();
                    ddItems.Items.Insert(0, "Select");
                }
            }
        }
    }
}