Sunday, 18 November 2012

Beginning .Net : Validate a DropDownList control using validation control in asp.net

There is a situation in drop down list where first item is "[Select]" and you need to make mandatory selection from drop down list except "[Select]".
Means, user must select value from drop down list but did not allow to select first element "[Select]". We can achieve this using required field validator control. For that we need to set "InitialValue" property.

Here is example for this.
In this example we take one product drop down list control in this list we list out all products, But the First Item is "[Select]" and it's value is "-1" in product drop downlist.
And We take one Required Field Validator control and set it's ValidateControl property to product drop down list id. We also set "InitialValue=-1" property.
We also took one button so that on click of button required field valdator control validate user input.
In this example we set InitialValue to -1 so that , if user select "[Select]" item from drop down list and click on "Save" button Validator control executed and validation message display on screen.
You can see that validation message in output.


ASPX Code :
            <b>Product : </b> <asp:DropDownList runat="server" ID="ddlProducts">
                <asp:ListItem Text="[Select]" Value="-1"></asp:ListItem>
                <asp:ListItem Text="TV" Value="1"></asp:ListItem>
                <asp:ListItem Text="Mouse" Value="2"></asp:ListItem>
                <asp:ListItem Text="Keyboard" Value="3"></asp:ListItem>
                <asp:ListItem Text="LCD" Value="4"></asp:ListItem>
            </asp:DropDownList>  
            <asp:RequiredFieldValidator runat="server" ID="rfvProduct" ControlToValidate="ddlProducts"
            ErrorMessage="Please Select Product." InitialValue="-1" ForeColor="Red" ></asp:RequiredFieldValidator>
            <br />
            <asp:Button runat="server" ID="btnSave" Text="Save" />

Output :


View article on "Allow only integer value in textbox using ASP.NET RegularExpressionValidator control". Click Here...
 
Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment

Post a Comment