需要TextBox取决于Repeater中的RadioButtonList选择

时间:2015-09-03 19:17:37

标签: c# asp.net repeater requiredfieldvalidator

我有一个带有RadioButtonList和TextBox的转发器。我希望只有当RadioButtonList的值为1或2时才需要TextBox。我该如何实现?

我认为我最初可以在选定的索引更改中启用RFV,但它无法查看项目,因为它在转发器内。我是否需要在ItemDataBound中执行此操作?

<asp:Repeater ID="repeaterSurvey" runat="server">
   <ItemTemplate>
      <div class="form-group">
         <asp:Label ID="labelQuestion" runat="server" Text='<%# Eval("Question")%>' />
         <asp:RequiredFieldValidator ID="RFV1" CssClass="required" runat="server" 
          ErrorMessage="Required" Display="Dynamic" ControlToValidate="surveyList" />

         <asp:RadioButtonList RepeatDirection="Horizontal" ID="surveyList" AutoPostBack="true"
          OnSelectedIndexChanged="surveyList_SelectedIndexChanged" runat="server">
            <asp:ListItem Value="1">Strongly Disagree</asp:ListItem>
            <asp:ListItem Value="2">Disagree</asp:ListItem>
            <asp:ListItem Value="3">Agree</asp:ListItem>
            <asp:ListItem Value="4">Strongly Agree</asp:ListItem>
            <asp:ListItem Value="0">N/A</asp:ListItem>
         </asp:RadioButtonList>
         <asp:HiddenField ID="hiddenfieldID" Value='<%# Eval("ID")%>' runat="server" />
         <asp:TextBox ID="textboxComment" Placeholder="Comments" CssClass="form-control" TextMode="MultiLine"
          Rows="3" runat="server"></asp:TextBox>
         <asp:RequiredFieldValidator ID="RFV2" Enabled="false" CssClass="required" runat="server"
          ErrorMessage="Comment Required" Display="Dynamic" ControlToValidate="textboxComment" />
      </div>
   </ItemTemplate>
</asp:Repeater>

代码隐藏

protected void surveyList_SelectedIndexChanged(object sender, System.EventArgs e)
{
   if (surveyList.SelectedValue == "1" || surveyList.SelectedValue == "2")
   {
      RFV2.Enabled = true;
   }
   else
   {
      RFV2.Enabled = false;
   }
}

1 个答案:

答案 0 :(得分:0)

在评论部分(stephen.vakil)的帮助下,我能够为我的问题创建解决方案:

protected void surveyList_SelectedIndexChanged(object sender, System.EventArgs e)
    {
            RadioButtonList surveyList = (RadioButtonList)sender;
            string value = surveyList.SelectedValue;
            RepeaterItem row = (RepeaterItem)surveyList.NamingContainer;

            if (value == "1" || value == "2")
            {
                ((RequiredFieldValidator)row.FindControl("RFV2")).Enabled = true;
            }
            else
            {
                ((RequiredFieldValidator)row.FindControl("RFV2")).Enabled = false;
            }
    }