开发者

multiple selection from listbox in c#

I was wondering how do i allow user to make only make 3 selection from a list box.I am looking at this code,i think there is some l开发者_开发问答ogic error to this but i cant see what went wrong as im new to this can someone please guide me or share some article with me so that i can work on this,thank you:)

my code

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


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


You could use an ASP.NET-CustomValidator for this:

Providing a client-validation function:

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);
} 

providing a server-validate function:

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

and the aspx part:

<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>


Saurabh is right, Set you Listbox property of SelectionMode to Multiple. This will allow you to make multiple selections from your listbox.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜