i have asked myself if there is an e开发者_如何学Pythonasy way to check if a ListBox has a maximum of 5 selected items. There must be at least one and at most 5 items selected.
Do i need a CustomValidator with server-side validation?
Many thanks in advance...
You can do it with a CustomValidator routine.
<asp:CustomValidator ID="ListBox5ItemsValidator" runat="server"
OnServerValidate="ListBox5ItemsValidator_ServerValidate"
ClientValidationFunction="ListBox5ItemsValidator_ClientValidate"
ControlToValidate="MyListBox">
</asp:CustomValidator>
Server-side code:
protected void ListBox5ItemsValidator_ServerValidate(
object source, ServerValidateEventArgs args) {
int selectionCount = 0;
foreach (ListItem item in MyListBox.Items) {
if (item.Selected) selectionCount++;
}
args.IsValid = (selectionCount >= 1 && selectionCount <= 5);
}
Client-side code:
function ListBox5ItemsValidator_ClientValidate(sender, args) {
var selectionCount = $('#<% =MyListBox.ClientID %> option:selected').length;
args.IsValid = (selectionCount >= 1 && selectionCount <= 5);
};
Replace MyListBox with the actual name of your ListBox that you want to validate. If your ListBox is contained inside of other container controls, you may need a little more work to reference the control both on the server and client side. For instance, if it is contained in a FormView control called FormView1, you would use
ListBox MyListBox = (ListBox)FormView1.FindControl("MyListBox");
精彩评论