简体   繁体   English

使用vb限制asp.net中列表框的项目选择

[英]limit item selection from listbox in asp.net using vb

i want to restrict the number of item selection from the listbox in asp.net using vb.我想使用 vb 限制从 asp.net 的列表框中选择项目的数量。 I was trying it using javascript. But, not working.我正在尝试使用 javascript。但是,没有用。 Need help需要帮忙

<asp:ListBox ID="lbprefferedlocation" runat="server" DataSourceID="locations" 
                DataTextField="City_Name" OnSelectedIndexChanged="chkCount(this)" DataValueField="City_Name" SelectionMode="Multiple"></asp:ListBox>
            <asp:HiddenField ID="hiddenChkCount" runat="server" />
            <asp:SqlDataSource ID="locations" runat="server" 
                ConnectionString="<%$ ConnectionStrings:JPConnString %>" 
                SelectCommand="SELECT [City_Name] FROM [State_Info]"></asp:SqlDataSource>



function chkCount(obj)
{
    if(obj.checked==true)
    {
        if( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value >= 5 )
        {
            alert('You cannot select more than 5 items.');
            obj.checked=false;
        }
        else
        {
            document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value = parseInt( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value ) + 1;
        }
    }
    else
    {
        document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value = parseInt( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value) - 1;
    }
}

You could use a CustomValidator :您可以使用CustomValidator

 <asp:CustomValidator ID="CV_CheckLocationCount" runat="server"
     ValidateEmptyText="true" 
     ClientValidationFunction="CheckLocationCount"
     OnServerValidate="CheckLocationCount" 
     ControlToValidate="lbprefferedlocation"
     EnableClientScript="true" 
     ErrorMessage="Select at least one and at most 5 locations"
     ValidationGroup="VG_SAVE">*
</asp:CustomValidator>

function CheckLocationCount(sender, args){
    var count=$('#<%=lbprefferedlocation.ClientID %> option:selected').length;
    args.IsValid = count > 0 && count <= 5;
} 

Edit : And here's a non jQuery solution:编辑:这是一个非 jQuery 解决方案:

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

You can use it in this way:你可以这样使用它:

var listBox  = document.getElementById("<%=lbprefferedlocation.ClientID %>");
args.IsValid = validateListBoxSelectionCount(listBox, 1, 5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM