Test if Item Selected in ListBox

Testing to ensure that a ListBox has a selected item on submit.

Here all is done using the built in asp.net functions.

Alternatively, could use JavaScript or JQuery. Note that to do so would need to assign variables to the listbox element for the testing.

1. Field Validator

Here’s the list box with its items. I find fruit and veg a ready source of names when trying out examples such as this.

<asp:ListBox ID="lbxFruit" runat="server">
        <asp:ListItem>Apple</asp:ListItem>
        <asp:ListItem>Plum</asp:ListItem>
        <asp:ListItem>Pear</asp:ListItem>
        <asp:ListItem>Peach</asp:ListItem>
        <asp:ListItem>Grape</asp:ListItem>
    </asp:ListBox>
    <asp:Button ID="btnSubmit" runat="server" Text="Button" />
    <asp:RequiredFieldValidator ID="rqdFruit" runat="server" 
        ControlToValidate="lbxFruit" Display="Dynamic" 
        ErrorMessage="Required! Please choose 1!">Required! Please choose 1</asp:RequiredFieldValidator>

With the RequiredFieldValidator using the Dynamic display option gives instant feedback if the field isn’t completed.

2. On Form Submit

If lbxFruit.SelectedIndex = -1 Then
Response.Write("Please select at least one item")
End If

In this example the form is submitted. The work is then done on the server to check whether the submission is correct.

Here the test is whether the SecletedIndex has a value of -1, ie not set.

For simplicity I have simply shown a response write. The presentation should be better with a label populated with the details of the field which has been selected, I assume that other fields will also be similarly tested.

Also I’ve not shown an abort. If there’s an error on the form then further actions on the field won’t be processed. The page will be returned back to the visitor as many times as needed until its correctly filled out.

3. JavaScript/JQuery

Custom javaScript or JQuery can be written.

To be able to make such actions the ID of fields the fields will be required. This will be done by assigning to a variable the reference on the page, as composed by asp.net.

var lbxFruit = document.getElementById(“<%= lbxFruit.ClientID %>”).innerText;

Thoughts

I prefer in practice to use a combination of the two examples above.

By first checking whether the use has filled out the form correctly the responses are immediate. The user experience is the better for it

and we impose less impact on the server.

Once the user input has been validated then it can be submitted to the server and checked. Checking is required because there’s the chance that the user input has escaped the validation and who knows maybe the page has been edited to enable the trial of input of bad data.