防止在多个下拉列表中选择相同的值

时间:2010-07-28 12:47:39

标签: .net drop-down-menu customvalidator

我有四个具有相同项目/值的下拉列表。我希望防止在上传表单时多次选择相同的值。如何使用自定义验证器执行此操作?谢谢!

3 个答案:

答案 0 :(得分:1)

我会提倡Kyra的第一个修改下拉列表的解决方案,以便无法选择相同的值,防止问题总是比告诉用户他们做错了更好。但是,如果您确实想要使用CustomValidator,则以下代码可以正常工作:

<asp:CustomValidator ID="dropDownValidation" runat="server" OnServerValidate="dropDownValidation_ServerValidate"
    ErrorMessage="The same value cannot be selected in more than one drop down." />

然后在后面的代码中,或脚本标记。

protected void dropDownValidation_ServerValidate(object sender, ServerValidateEventArgs e)
{
    e.IsValid = !haveSameValue(DropDownList1.SelectedValue, DropDownList2.SelectedValue) &&
                !haveSameValue(DropDownList1.SelectedValue, DropDownList3.SelectedValue) &&
                !haveSameValue(DropDownList1.SelectedValue, DropDownList4.SelectedValue) &&
                !haveSameValue(DropDownList2.SelectedValue, DropDownList3.SelectedValue) &&
                !haveSameValue(DropDownList2.SelectedValue, DropDownList4.SelectedValue) &&
                !haveSameValue(DropDownList3.SelectedValue, DropDownList4.SelectedValue);
}

protected bool haveSameValue(string first, string second)
{
    if (first != null && second != null)
    {
        return first.Equals(second);
    }

    return first == null && second == null;
}

这显然可以进一步完善,如果需要,可以使用javascript函数提供客户端验证,使用ClientValidationFunction属性。

答案 1 :(得分:0)

这可能不是最佳答案,但您始终可以在每个下拉列表中添加一个actionlistener,以便在下拉列表中选择更改时调用它。

这样,当第二个下拉列表中的选定元素发生更改时,它会调用其actionlistener,然后在其中重置其他下拉列表,以便它们不会显示所选值,或者如果可能,则设置它以便您无法选择那个价值

OR

当其中一个下拉列表的选择发生更改时,您会检查其是否与其他下拉列表中的其他所选值相等,如果是,则要么向用户显示msgbox和/或更改选择到空白选择或第一个尚未使用的可用值。

答案 2 :(得分:0)

关于haveSameValue函数的一些工作。这似乎对我有用。谢谢你的帮助。

 protected bool haveSameValue(string first, string second)

{
if (!string.IsNullOrEmpty(first) & !string.IsNullOrEmpty(second) && first.Equals(second)) {
    return first.Equals(second);
}

}

相关问题