Search code examples
c#asp.netrequiredfieldvalidator

InitialValue does not set in RequiredFieldValidator DDL


For some reason the dropdownlist's initial value doesnt get set. It always loads some random value instead. When I look into the markup I can see all the list items including the one with -1 value. I also tried clearing browser cache and explicitly setting the SelectedIndex/Value in code to 0/"-1", but cant seem to figure out what is going on. Any idea?

Here is how I am doing it:

<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="LoadGenders">
                            </asp:DropDownList>
                            <div class="error"> 
                                <asp:RequiredFieldValidator                                     
                                    ID="RequiredFieldValidatorGender"
                                    Runat="server"
                                    Enabled="true"
                                    InitialValue="-1"
                                    ControlToValidate="ddlGender"
                                    SetFocusOnError="true"                                        
                                    Display="Dynamic">Gender Required</asp:RequiredFieldValidator>
                            </div>

Generated HTML:

<select name="pagecolumns_0$pagecontent_1$contentleftcol_0$ctl00$ddlGender" id="pagecolumns_0_pagecontent_1_contentleftcol_0_ctl00_ddlGender" class="select_Box">
<option value="-1">--Select Gender--</option>
<option selected="selected" value="M">Male</option>
<option value="F">Female</option></select>

as you can see, it is randomly selecting Male. Alsow, I notice that, last time I fill the form I set it to Male before hitting submit. May be is it caching the selection?

Here is the .cs:

protected void LoadGenders(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            ((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
        }
public static ListItem[] GenderWithSelect = (new[] { new ListItem("--Select Gender--", "-1") }).Concat(Gender).ToArray();
 public static ListItem[] Gender = new[]
                                              {
                                                  (new ListItem("Male","M")),
                                                  (new ListItem("Female","F"))
                                              };



Solution

  • It turns out it has something to do with load sequence of the controls. So, adding selectedindex to LoadGenders did the trick.

    protected void LoadGenders(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            ((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
            ((DropDownList) sender).SelectedIndex = 0;
        }