Home > ASP.Net, Javascript, Uncategorized > Limit Number of items to be Selected in ASP.Net ListBox

Limit Number of items to be Selected in ASP.Net ListBox


Hi all,

try this example to Limit Number of items to be Selected in ASP.Net ListBox using Client and Server side validation


<script type="text/javascript" language="javascript">
function CustomValidator1_ClientValidate(source,args)
{ 
var listbox = document.getElementById("<%=ListBox1.ClientID %>");
var total = 0;
var i=0;
for( i = 0; i < listbox.options.length; i++ )
{
 if (listbox.options[i].selected) 
 {
 total ++; 
 if (total >10) {
 args.IsValid = false;
 return;
 }
 } 
 } 
 args.IsValid = true; return;
}
</script>

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" Height="100%"
Width="100%"></asp:ListBox>
<asp:Button ID="btn_Save" runat="server" Text="Save" />
<asp:CustomValidator ID="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="Please select 10 items only."
ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

In Code behind :

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
int count = 0;
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
count++;
}
args.IsValid = (count > 10) ? false : true;
}

Hope this helps

Good Luck

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: