选择dropdownlist1上的某个项目后,自动选择dropdownlist2上的某个项目

时间:2019-07-12 11:44:14

标签: c# asp.net webforms

我想在下拉列表1上选择项x5时,在下拉列表2上自动选择项y0

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_Itemchanged">
                        <asp:ListItem Value='5'>x5</asp:ListItem>
                        <asp:ListItem Value="4">x4</asp:ListItem>
                        <asp:ListItem Value="3">x3</asp:ListItem>
                        <asp:ListItem Value="2">x2</asp:ListItem>
                        <asp:ListItem Value="1">x1</asp:ListItem>
</asp:DropDownList>

<asp:DropDownList ID="DropDownList2" runat="server">
                        <asp:ListItem Value="0.75">y0.75</asp:ListItem>
                        <asp:ListItem Value="0.50">y0.50</asp:ListItem>
                        <asp:ListItem Value="0.25">y0.25</asp:ListItem>
                        <asp:ListItem Value="0">y0</asp:ListItem>
</asp:DropDownList>

protected void DropDownList1_Itemchanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedItem.Value == "5")
        {
            DropDownList2.Items.FindByValue("0").Selected = true;
            DropDownList2.Items.FindByValue("0.75").Attributes.Add("Disabled", "Disabled");
            DropDownList2.Items.FindByValue("0.50").Attributes.Add("Disabled", "Disabled");
            DropDownList2.Items.FindByValue("0.25").Attributes.Add("Disabled", "Disabled");
        }
    }

当我在dropdownlist1上选择项x4,并在dropdownlist2上选择项y0.25,之后,当我在dropdownlist1上选择x5时,它提示我“不能在DropDownList中选择多个项目”

1 个答案:

答案 0 :(得分:1)

使用列表上的SelectedValue属性:

protected void DropDownList1_Itemchanged(object sender, EventArgs e)
{
    if (DropDownList1.SelectedItem.Value == "5")
    {
        DropDownList2.SelectedValue = "0";
    }
}