65.9K
CodeProject is changing. Read more.
Home

Validate comboBox with Initial Value and RequiredFieldValidator

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 6, 2014

CPOL
viewsIcon

10910

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:

<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:

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: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