views:

786

answers:

2

Hi all,

I am creating a web control in vb.net that contains a list box. I know that I am able to choose a selection mode of Single or Multiple, but I am interested in limiting a Multiple selection to a predetermined size. For example preventing a user from selecting more than 3 items.

I have tried adding a Validator to the list box, which might be a way forward, but was wondering if there was a way of changing the selection mode to something a bit different than just the two specified ones.

Any ideas or suggestions would be greatly appreciated

Edit: Unfortunately due to project limitations I am unable to use Javascript on this problem. very annoying I know!

+1  A: 

You could try handling one of the SelectedIndexChange events. With multiple selection, each time this event fires you can check how many items have already been selected. If it is more than you want, have the handler deselect the one that was just selected. You could also put up a little red label under the listbox saying "Sorry, no more than [n] selections allowed."

EDIT: Just noticed you said WEB. Same theory applies, but it would have to be done using Javascript.

Dave Swersky
Thanks for that. Only problem is I am unable to use Javascript on this problem due to (annoying) project limitations.
chillysapien
In that case, you *may* be able to use Autopostback, but I'm not sure if that will work for multiple selection. Is AJAX an option? That could work as well.
Dave Swersky
@Dave: I don't see why it would be much different on the web. If the listbox is set up with AutoPostBack set to true, it should fire each time a selection is made. Then you can run the validation code during the postback (or partial postback in AJAX).
TheTXI
A: 

On the SelectedIndexChanged event, write a short piece of code that will check the number of selected items and if it is greater than your desired amount, unselect the new selection (or unselect the oldest one, or however you wish this to operate).

TheTXI