This blog will show you, how you can validate a list box, using RequiredFieldValidator control in ASP.NET. Thus, for this blog, we will create ASP.NET Application, add a listbox and a RequiredFieldValidator control.
- <asp:ListBox ID = "ListBox1" runat = "server" Width="200" Height="150" SelectionMode = "Multiple">
- <asp:ListItem Value="1">Item 1</asp:ListItem>
- <asp:ListItem Value="2">Item 2</asp:ListItem>
- <asp:ListItem Value="3">Item 3</asp:ListItem>
- <asp:ListItem Value="4">Item 4</asp:ListItem>
- <asp:ListItem Value="5">Item 5</asp:ListItem>
- <asp:ListItem Value="6">Item 6</asp:ListItem>
- <asp:ListItem Value="7">Item 7</asp:ListItem>
- <asp:ListItem Value="8">Item 8</asp:ListItem>
- </asp:ListBox>
-
- <asp:RequiredFieldValidator ID = "RequiredFieldValidator1" ControlToValidate ="ListBox1" InitialValue = "" runat="server" ErrorMessage = "Please select some items" ForeColor="Red"></asp:RequiredFieldValidator>
- <br />
- <hr />
- <asp:Button ID="Button1" runat="server" Text="Submit" />
In the code, mentioned above, I specified the control to validate. In validation, it will display the error message. Now, we will run the Application to check the output.