簡體   English   中英

如何在C#中驗證ASP.NET中繼器中的多個單選按鈕

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

我有多個單選按鈕,並且正在使用GroupName來選擇2個選項中的至少一個。 我似乎無法獲得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;
         }
     }
 }

您必須將發件人對象轉換為自定義驗證器:

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)
    {
        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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM