简体   繁体   English

如何从查询结果创建DropDownList?

[英]How to create DropDownList From query result?

I have the following query: 我有以下查询:

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);
    }

I select a value from ddl1 and I need to create another one using the result of the query. 我从ddl1选择一个值,然后需要使用查询结果创建另一个值。 What do I do? 我该怎么办?

Assuming the result of the query returns 2 column from the database: UserID,UserName The Column is indexed in the dataset table from left to right from index 0 to increasing order. 假设查询结果从数据库返回2列:UserID,UserName列在数据集表中从左到右从索引0到升序进行索引。 Suppose your dropdownlist control ID="ddlShowResult" then use the following code: 假设您的dropdownlist控件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();
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM