如何基于另一个下拉列表填充下拉列表

本文关键字:下拉列表 填充 另一个 何基于 | 更新日期: 2023-09-27 18:01:27

我正在做一个基于项目列表的销售订单。我有两个下拉列表。第一个下拉列表从Projects Table中检索数据。第二个下拉列表是根据从第一个下拉列表中选择的值填充数据。

下面显示了项目和任务下拉列表的源代码。


    <!--Project-->
    <div class="form-group">
        <label class="control-label col-lg-4">
            Project</label>
        <div class="col-lg-8">
            <asp:DropDownList ID="ddlProjects" runat="server" class="form-control" 
                AutoPostBack="True" DataTextField="Select a project..." DataValueField="AutoId" 
                onselectedindexchanged="ddlProjects_SelectedIndexChanged" />
        </div>
    </div>
    <!--Tasks-->
    <div class="form-group">
        <label class="control-label col-lg-4">
            Task</label>
        <div class="col-lg-8">
            <asp:DropDownList ID="ddlTasks" runat="server" class="form-control" />
        </div>
    </div>

下面显示了下拉列表 背后的代码
void GetProjects()
{
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "SELECT ProjectID, Name FROM Projects WHERE Status = 'On Going'";
    SqlDataReader dr = cmd.ExecuteReader();
    ddlProjects.DataSource = dr;
    ddlProjects.DataTextField = "Name";
    ddlProjects.DataValueField = "ProjectID";
    ddlProjects.DataBind();
    con.Close();
}
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    var ID = int.Parse(ddlProjects.SelectedValue);
    string sql = "SELECT TaskID, Name FROM ProjectTasks WHERE ProjectID = @ProjectID";
    SqlCommand cmd = new SqlCommand(sql, con);
    cmd.Connection = con;
    SqlDataAdapter ad = new SqlDataAdapter(cmd);
    cmd.Parameters.AddWithValue("@ProjectID", ID);
    ad.Fill(table);
    ddlTasks.DataTextField = "Name";
    ddlTasks.DataSource = table;
    ddlTasks.DataBind();
}

问题是,每次我打开销售订单表单,默认的DataTextValue不是我在源代码中声明的是"选择一个项目",而是显示第一个记录。

另一件事是,我觉得代码仍然有问题,只是我不能确定是哪一个。

如何基于另一个下拉列表填充下拉列表

您需要从aspx中删除DataTextField="Select a project..." DataValueField="AutoId"。你可以在你的代码中定义它。

添加第一个选项并设置AppendDataBoundItems = true

ddlProjects.Items.Add(new ListItem("Select a project...",""));
ddlProjects.AppendDataBoundItems = true;
ddlProjects.DataSource = dr;
ddlProjects.DataTextField = "Name";
ddlProjects.DataValueField = "ProjectID";
ddlProjects.DataBind();

确保空项没有被选中

protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
    ddlTasks.Items.Clear();
    int ID = 0;
    if (int.TryParse(ddlProjects.SelectedValue, out ID))
    {
        DataTable table = new DataTable();
        string sql = "SELECT TaskID, Name FROM ProjectTasks WHERE ProjectID = @ProjectID";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Connection = con;
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        cmd.Parameters.AddWithValue("@ProjectID", ID);
        ad.Fill(table);
        ddlTasks.DataTextField = "Name";
        ddlTasks.DataSource = table;
        ddlTasks.DataBind();
    }
}