参数SQL查询下拉列表

时间:2016-04-11 22:15:44

标签: c# asp.net sql-server drop-down-menu parameters

所以,我终于得到了以下代码。它根据DDL的选定值运行不同的查询。不,确定它是否是最好的方法。无论如何,我如何直接在下面的查询中使用参数?

我希望能够参数化dbname和数据库本身。感谢。

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (DropDownList1.SelectedValue == "")
    {
        {
            DataTable dt = new DataTable();
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    if (DropDownList1.SelectedValue == "db1")
    {
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db1ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("select db1.dbo.table1.dbname where dbname = 'testdb1' ", con);
            SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            Adpt.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
    else if (DropDownList1.SelectedValue == "db2")
    {
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("select db2.dbo.table1.dbname where dbname = 'testdb2' ", con);
            SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            Adpt.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

1 个答案:

答案 0 :(得分:-2)

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    SqlDataAdapter Adpt;
    if(DropDownList1.SelectedValue == string.Empty)
    {
        //return; 
        //GridView1.DataSource = dt;
        //GridView1.DataBind();
    }
    if(DropDownList1.SelectedValue == "db1")
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db1ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select db1.dbo.table1.dbname where dbname = 'testdb1' ", con);
        Adpt = new SqlDataAdapter(cmd);
        new SqlDataAdapter(cmd).Fill(dt);
    }
    else if(DropDownList1.SelectedValue == "db2")
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select db2.dbo.table1.dbname where dbname = 'testdb2' ", con);
        Adpt = new SqlDataAdapter(cmd);
        new SqlDataAdapter(cmd).Fill(dt);
    }
    GridView1.DataSource = dt;
    GridView1.DataBind();
}