In Asp.net, sometimes we need to validate ListBox and DropDown List using Required field validator. It is tricky and avoids the use of JavaScript function to validate ListBox and DropDown List. Here I am sharing the code.
<form id="form1" runat="server"> <div> <asp:ListBox ID="lstboxCity" runat="server" Width="200px" SelectionMode="Multiple"> <asp:ListItem Value="1">Delhi</asp:ListItem> <asp:ListItem Value="2">Noida</asp:ListItem> <asp:ListItem Value="3">Gurgaon</asp:ListItem> <asp:ListItem Value="4">Mumbai</asp:ListItem> <asp:ListItem Value="5">Pune</asp:ListItem> <asp:ListItem Value="6">Banglore</asp:ListItem> <asp:ListItem Value="7">Lucknow</asp:ListItem> </asp:ListBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="lstboxCity" InitialValue="" runat="server" ErrorMessage="Please select atleast one city"></asp:RequiredFieldValidator> </div> <br /> <div> <asp:DropDownList ID="ddlCity" runat="server" Width="200px"> <asp:ListItem Value="0">--Select--</asp:ListItem> <asp:ListItem Value="1">Delhi</asp:ListItem> <asp:ListItem Value="2">Noida</asp:ListItem> <asp:ListItem Value="3">Gurgaon</asp:ListItem> <asp:ListItem Value="4">Mumbai</asp:ListItem> <asp:ListItem Value="5">Pune</asp:ListItem> <asp:ListItem Value="6">Banglore</asp:ListItem> <asp:ListItem Value="7">Lucknow</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="ddlCity" InitialValue="0" runat="server" ErrorMessage="Please select city"></asp:RequiredFieldValidator> </div> <br /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> </form>
In this article I try to explain how to validate DropDownList and ListBox using Required Field Validator. I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.