Search code examples
asp.netdropdownlistfor

how to prevent dropdownlists with same set of values select same value?


I have 3 dropdowns and each one is populated with same set of values say a,b and c

eg: if i select 'a' from the dropdown and there is another dropdown with the same value 'a' selected. i should get an err msg.

How is this possible.


Solution

  • Use CompareValidator control like this:

    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="ddl1" runat="server">
                <asp:ListItem Text="a" Value="a"></asp:ListItem>
                <asp:ListItem Text="b" Value="b"></asp:ListItem>
            </asp:DropDownList>
            <asp:DropDownList ID="ddl2" runat="server">
                <asp:ListItem Text="a" Value="a"></asp:ListItem>
                <asp:ListItem Text="b" Value="b"></asp:ListItem>
            </asp:DropDownList>
            <asp:DropDownList ID="ddl3" runat="server">
                <asp:ListItem Text="a" Value="a"></asp:ListItem>
                <asp:ListItem Text="b" Value="b"></asp:ListItem>
            </asp:DropDownList>
            <asp:CompareValidator ID="CompareValidator1" runat="server"
                ErrorMessage="DropDownList 1 can't be equal DropDownList 2"
                ControlToCompare="ddl1" ControlToValidate="ddl2" Operator="NotEqual"></asp:CompareValidator>
            <asp:CompareValidator ID="CompareValidator2" runat="server"
                ErrorMessage="DropDownList 2 can't be equal DropDownList 3"
                ControlToCompare="ddl2" ControlToValidate="ddl3" Operator="NotEqual"></asp:CompareValidator>
             <asp:CompareValidator ID="CompareValidator3" runat="server"
                ErrorMessage="DropDownList 1 can't be equal DropDownList 3"
                ControlToCompare="ddl2" ControlToValidate="ddl3" Operator="NotEqual"></asp:CompareValidator>
        </div>
    </form>