c#中从列表框中进行多项选择

时间:2011-06-29 09:32:58

标签: asp.net listbox multipleselection

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

我的代码

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

3 个答案:

答案 0 :(得分:2)

<asp:ListBox SelectionMode="Multiple"></asp:ListBox>  

答案 1 :(得分: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>

答案 2 :(得分:2)

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