如何从查询结果创建DropDownList?

时间:2018-03-02 12:49:55

标签: c# asp.net

我有以下查询:

protected void Filterbtn_Click(object sender, EventArgs e)
{
    string commandFilterUsers = "SELECT DISTINCT " + ddlFilterUsers.SelectedValue + " FROM UsersDB";
    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open(); 
        SqlCommand sqlCommand = new SqlCommand(commandFilterUsers, connection);
        SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand);
        adapter.Fill(dataset);
    }

我从ddl1中选择一个值,我需要使用查询结果创建另一个值。我该怎么办?

1 个答案:

答案 0 :(得分:0)

假设查询结果从数据库中返回2列: 用户名,用户名 列从数据集表中从左到右从索引0索引到递增顺序。 假设您的下拉列表控件 ID =“ddlShowResult”然后使用以下代码:

      protected void Filterbtn_Click(object sender, EventArgs e)
            {
                string commandFilterUsers = "SELECT DISTINCT " + ddlFilterUsers.SelectedValue + " FROM UsersDB";
                string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand sqlCommand = new SqlCommand(commandFilterUsers, connection);
                    SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand);
                    adapter.Fill(dataset, "FillUser");
                }
                ddlShowResult.DataTextField = dataset.Tables["FillUser"].Columns[1].ToString();//User Name: Will be shown to user
                ddlShowResult.DataValueField = dataset.Tables["FillUser"].Columns[0].ToString();//User ID: will be used in backend
                ddlShowResult.DataSource = dt;
                ddlShowResult.DataBind();
            }