2

我想知道如何允许用户从列表框中只进行 3 次选择。我正在查看这段代码,我认为这有一些逻辑错误,但我看不出哪里出了问题,因为我是新手,有人可以请指导我或与我分享一些文章,以便我可以解决这个问题,谢谢:)

我的代码

if (listBox1.SelectedIndex <= 4)
     errorProvider1.SetError(listBox1, "Please pick 1.");
else
     errorProvider1.SetError(listBox1, "");
4

3 回答 3

2
<asp:ListBox SelectionMode="Multiple"></asp:ListBox>  
于 2011-06-29T09:36:58.007 回答
2

您可以为此使用ASP.NET-CustomValidator

提供客户端验证功能:

function validateSelectionCount(sender, args){
    var listbox = document.getElementById('ListBox1');
    args.IsValid = validateListBoxSelectionCount(listbox, 3, 3);
} 

function validateListBoxSelectionCount(listbox, minSelected, maxSelected){
    var selected=0;
    if(listbox != null){
        for (var i=0; i<listbox.length; i++){
            if(listbox.options[i].selected){
               selected++; 
               if(selected>maxSelected)break;
            }
        }
    }
   return (selected >= minSelected && selected <= maxSelected);
} 

提供服务器验证功能:

Protected Sub validateSelectionCount(ByVal source As Object, ByVal args As ServerValidateEventArgs)
    Dim count As Int32 = 0
    Dim maxCount As Int32 = 3
    Dim minCount As Int32 = 3
    Dim lb As ListBox = DirectCast(Me.FindControl(DirectCast(source, CustomValidator).ControlToValidate), ListBox)
    For Each item As ListItem In lb.Items
        If item.Selected Then count += 1
        If count > maxCount Then Exit For
    Next
    args.IsValid = (count >= minCount AndAlso count <= maxCount)
End Sub

和 aspx 部分:

<asp:ListBox ID="ListBox1" CausesValidation="true" ValidationGroup="VG_SAVE" runat="server" CssClass="content" SelectionMode="Multiple"></asp:ListBox>
<asp:CustomValidator ID="CV_SelectionCount" runat="server" ValidateEmptyText="true" ClientValidationFunction="validateSelectionCount" OnServerValidate="validateSelectionCount" ControlToValidate="ListBox1" Display="None" EnableClientScript="true" ErrorMessage="Select 3 items" Style="visibility: hidden" ValidationGroup="VG_SAVE">*</asp:CustomValidator>
于 2011-06-29T09:42:15.903 回答
2

Saurabh 是对的,将 SelectionMode 的 Listbox 属性设置为 Multiple。这将允许您从列表框中进行多项选择。

于 2011-06-29T09:42:58.000 回答