RequiredFieldValidator To Validate ListBox In ASP.NET

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. 
  1. <asp:ListBox ID = "ListBox1" runat = "server" Width="200" Height="150" SelectionMode = "Multiple">  
  2.        <asp:ListItem Value="1">Item 1</asp:ListItem>  
  3.        <asp:ListItem Value="2">Item  2</asp:ListItem>  
  4.        <asp:ListItem Value="3">Item  3</asp:ListItem>  
  5.        <asp:ListItem Value="4">Item 4</asp:ListItem>  
  6.        <asp:ListItem Value="5">Item  5</asp:ListItem>  
  7.        <asp:ListItem Value="6">Item 6</asp:ListItem>  
  8.        <asp:ListItem Value="7">Item  7</asp:ListItem>  
  9.        <asp:ListItem Value="8">Item  8</asp:ListItem> 
  10.    </asp:ListBox>   
  11.   
  12.    <asp:RequiredFieldValidator ID = "RequiredFieldValidator1" ControlToValidate ="ListBox1" InitialValue = ""  runat="server" ErrorMessage = "Please select some items" ForeColor="Red"></asp:RequiredFieldValidator>  
  13.    <br />  
  14.    <hr />  
  15.    <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.
 
output
Ebook Download
View all
Learn
View all