简体   繁体   中英

Disable RequiredFieldValidator in asp.net c#

I am trying to disable a RequiredFieldValidator by radio button list value. I have it coded but it doesn't seems to be working.

What i have done so far:

protected void radioButtonList(object sender, EventArgs e)
        {
  if (((RadioButtonList)dvInsertPromotion.FindControl("RadioButtonList2")).SelectedValue == "Y")
            {
                ((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate1")).Enabled = false;
                ((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate")).Enabled = false;
                this.addPromotion.Show();
            }
            else
            {
                ((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate1")).Enabled = true;
                ((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate")).Enabled = true;
                this.addPromotion.Show();
            }
}

html:

 <asp:RadioButtonList ID="RadioButtonList2" runat="server" ValidationGroup="addValidationGp" OnSelectedIndexChanged="radioButtonList">
                                     <asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
                                     <asp:ListItem Text="No" Value="N" Selected></asp:ListItem>
</asp:RadioButtonList>
                                    <asp:TextBox ID="txtPubDate" Width="75"  MaxLength="10" runat="server" AutoPostBack="true" OnTextChanged="insertStartEndDateTime_SelectedIndexChanged"/>
                                <asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtPubDate"
                                    PopupPosition="Right" Format="dd/MM/yyyy" />
                                <asp:RequiredFieldValidator ID="rfvdate" ValidationGroup="addValidationGp" runat="server"
                                    ControlToValidate="txtPubDate" ErrorMessage="*" Display="Dynamic" Enabled="true"
                                    SetFocusOnError="true" /><br />

I've had the same problem in the past and the only way I was able to solve this was by making the validators invisible altogether:

 ((RequiredFieldValidator)dvInsertPromotion.FindControl("rfvdate1")).Visible = false;

Just don't forget to set them to visible again whenever you want to enable them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM