简体   繁体   中英

How do I validate multiple radio buttons in a ASP.NET repeater in C#

I have multiple radio buttons and I'm using a GroupName to choose at least 1 of the 2 options. I can't seem to get the GroupName so I can validate to make sure 1 of 2 has been selected with a submit button is >clicked.

 <myRepeater>

     <asp:CustomValidator 
       ID="CustomValidator1" 
       runat="server" 
       ErrorMessage="* Select an option" 
       ForeColor="#ff0000" 
       OnServerValidate="option1_Validation" 
       Display="Dynamic" /> 

     <asp:RadioButton 
       ID="rdOption1" 
       Text="Option_1" 
       GroupName="gnOption1" 
       runat="server" />

     <asp:RadioButton 
       ID="rdOption2" 
       Text="Option_2" 
       GroupName="gnOption1" 
       runat="server" />

 </myRepeater>

Code:

 protected void option1_Validation(object source, ServerValidateEventArgs args)
 {
     bool itemSelected = false;
     foreach (RepeaterItem ri in myRepeater.Items)
     {
         RadioButton rb= (RadioButton)ri.FindControl("gnOption1");
         {               
             if (rb.GroupName == "gnOption1" && rb.Checked == true)
             {
                  itemSelected = true; 
             }
             args.IsValid = itemSelected;
         }
     }
 }

You'll have to cast the sender object as a Custom Validator:

CustomValidator myCustomValidator = (CustomValidator)sender;

Then find the parent of the CustomValidator, in this case the Repeater Item:

RepeaterItem ri = (RepeaterItem)myCustomValidator.Parent;

And finally get the control:

RadioButton rb= (RadioButton)ri.FindControl("gnOption1");

You'll have to adjust it to your needs.

protected void game1_Validation(object sender, ServerValidateEventArgs args)
    {
        CustomValidator CustomValidator1 = (CustomValidator)sender;
        bool itemSelected = false;
        RepeaterItem ri = (RepeaterItem)CustomValidator1.Parent;         
        {
            if (ri is RadioButton)
            {
                RadioButton rb = (RadioButton)ri.FindControl("gnOption11");
                if (rb.GroupName == "gnOption1" && rb.Checked == true)
                {
                    itemSelected = true;
                }
            }
        }
        args.IsValid = itemSelected;
    }

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