Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Validate comboBox with Initial Value and RequiredFieldValidator

0.00/5 (No votes)
6 Nov 2014CPOL 10.9K  
Validate comboBox with Initial Value and RequiredFieldValidator

When you need to validate a comboBox in your aspx, you need to use the InitialValue property in order to ignore this first item by default Sin títulowhen the RequiredFieldValidator is going to validate it. Here is an example of that:

XML
<telerik:RadComboBox ID="rcbProduct" 
DataTextField="nombre" Width="100%" DataValueField="ProductId"
    runat="server" AppendDataBoundItems="false">
</telerik:RadComboBox>

<asp:RequiredFieldValidator runat="server" 
ID="RequiredFieldValidator10" ValidationGroup="ValidationProduct"
    ControlToValidate="rcbProduct" ErrorMessage="Error"
Display="None" 
InitialValue="Choose a Product"></asp:RequiredFieldValidator>

<asp:ImageButton ID="btnSave" runat="server"
    OnClick="btnSave_Click" ValidationGroup="ValidationProduct"
CausesValidation="true" Visible="true" />

<asp:ValidationSummary ID="ValidationSummaryOrdenReferencia" 
runat="server" ShowMessageBox="true"
    ShowSummary="false" ValidationGroup="ValidationProduct" />

You will need to load your dropdown in C# server side, with an objectDataSource or with a list in your page load event:

C#
RadComboBox comboProduct = DvProducts.FindControl("rcbProduct") as RadComboBox;
List<DAL.Product> ProductList = classProduct.GetProductList();

comboProduct.AppendDataBoundItems = true;
comboProduct.Items.Clear();
comboProduct.Items.Add(new RadComboBoxItem("Choose a Product", "-1"));
comboProduct.DataSource = ProductList;
comboProduct.DataBind();
comboProduct.SelectedIndex = -1;
comboProduct.Enabled = true;

A second way to load the dropdown is as follows:

ASP.NET
<asp:DropDownList runat="server" id="rcbProduct">
    <asp:ListItem Value="0" text="Choose a Product">
    <asp:ListItem Value="1" text="Product A">
    <asp:ListItem Value="2" text="Product B">
</asp:DropDownList>

<asp:RequiredFieldValidator ID="rcbProduct" 
runat="Server" InitialValue="0"
ControlToValidate="rcbProduct">
</asp:RequiredFieldValidator>

If this post helped you, please leave a comment.

Filed under: .NET, CodeProject, Telerik

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)