Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could use an <a href="http://msdn.microsoft.com/en-us/library/9eee01cx%28v=vs.71%29.aspx" rel="nofollow">ASP.NET-CustomValidator</a> for this:</p> <p>Providing a client-validation function:</p> <pre><code>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&lt;listbox.length; i++){ if(listbox.options[i].selected){ selected++; if(selected&gt;maxSelected)break; } } } return (selected &gt;= minSelected &amp;&amp; selected &lt;= maxSelected); } </code></pre> <p>providing a server-validate function:</p> <pre><code>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 &gt; maxCount Then Exit For Next args.IsValid = (count &gt;= minCount AndAlso count &lt;= maxCount) End Sub </code></pre> <p>and the aspx part:</p> <pre><code>&lt;asp:ListBox ID="ListBox1" CausesValidation="true" ValidationGroup="VG_SAVE" runat="server" CssClass="content" SelectionMode="Multiple"&gt;&lt;/asp:ListBox&gt; &lt;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"&gt;*&lt;/asp:CustomValidator&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload