为什么drop-down在每次回发时都保留旧值

本文关键字:保留 drop-down 为什么 | 更新日期: 2023-09-27 18:20:13

当我点击另一个下拉列表中的值时,我正在填写下拉列表,例如国家/城市关系,但问题是它在点击前加载相关值,但如果我在父下拉列表中更改值,它也会附加旧值。例如,如果我在母下拉列表中选择美国,拉斯维加斯等,但如果我点击巴基斯坦,它会加载巴基斯坦城市和美国城市,比如附件,为什么?

代码:

 protected void drpAgainstDistrict_SelectedIndexChanged(object sender, EventArgs e)//against district drop down selected index changed event
    {
        if (txtSelectedID.Text != "")
        {
            MyComplaints obj = new MyComplaints();
            int ID = Convert.ToInt32(drpAgainstDistrict.SelectedValue);
            DataSet ds = obj.SelectHomePoliceStaions(ID);
            drpAgainstPoliceStation.DataTextField = "PsName";
            drpAgainstPoliceStation.DataValueField = "ID";
            drpAgainstPoliceStation.DataSource = ds.Tables[0];
            drpAgainstPoliceStation.DataBind();
            HiddenFieldShowHideButtons.Value = "True";
        }
        else 
        {
            MyComplaints obj = new MyComplaints();
            int ID = Convert.ToInt32(drpAgainstDistrict.SelectedValue);
            DataSet ds = obj.SelectHomePoliceStaions(ID);
            drpAgainstPoliceStation.DataTextField = "PsName";
            drpAgainstPoliceStation.DataValueField = "ID";
            drpAgainstPoliceStation.DataSource = ds.Tables[0];
            drpAgainstPoliceStation.DataBind();
        }
    }

.aspx

<label>Relevant District</label>
<asp:DropDownList ID="drpAgainstDistrict" runat="server"
                  Width="178px" AutoPostBack="True"
                  OnSelectedIndexChanged="drpAgainstDistrict_SelectedIndexChanged">
</asp:DropDownList>
<label>Relevant Police Station</label>
<asp:DropDownList ID="drpAgainstPoliceStation" runat="server"
                  Width="178px" AppendDataBoundItems="true">
    <asp:ListItem Text="-Select-" Value="-1"></asp:ListItem>
</asp:DropDownList>

为什么drop-down在每次回发时都保留旧值

因为ViewState。只需清除Dropdownlist。yourDropdownList.Items.Clear();

您确实指定了AppendDataBoundItems="true"。文档指出,这"指示是否在数据绑定之前清除列表项",在您的情况下,它将在不首先清除列表的情况下附加列表项。

来源:ListControl.AppendDataBoundItems属性

我的建议是用UpdatePanel包装级联下拉列表。

由于AppendDataBoundItems="true"更改为AppendDataBoundItems="false"