猿问

如何在 C# 中验证 ASP.NET 中继器中的多个单选按钮

我有多个单选按钮,我使用 GroupName 来选择至少 2 个选项中的 1 个。我似乎无法获得 GroupName,因此我可以验证以确保已通过提交按钮选择了 2 个中的 1 个。


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

代码:


 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;

         }

     }

 }


九州编程
浏览 119回答 2
2回答

PIPIONE

您必须将发件人对象转换为自定义验证器:CustomValidator myCustomValidator = (CustomValidator)sender;然后找到 CustomValidator 的父项,在本例中为 Repeater Item:RepeaterItem ri = (RepeaterItem)myCustomValidator.Parent;最后获得控制权:RadioButton rb= (RadioButton)ri.FindControl("gnOption1");您必须根据自己的需要进行调整。

皈依舞

protected void game1_Validation(object sender, ServerValidateEventArgs args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; CustomValidator CustomValidator1 = (CustomValidator)sender;&nbsp; &nbsp; &nbsp; &nbsp; bool itemSelected = false;&nbsp; &nbsp; &nbsp; &nbsp; RepeaterItem ri = (RepeaterItem)CustomValidator1.Parent;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (ri is RadioButton)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RadioButton rb = (RadioButton)ri.FindControl("gnOption11");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (rb.GroupName == "gnOption1" && rb.Checked == true)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; itemSelected = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; args.IsValid = itemSelected;&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答