【问题标题】:when i try to check if a radio button is checked, the code doesnt execute当我尝试检查是否选中了单选按钮时,代码不执行
【发布时间】:2012-02-02 06:03:27
【问题描述】:

我正在尝试 2 在 asp.net 中进行测验。 mcq 选择 r 使用单选按钮显示。在后面的代码中,当我尝试 2 检查是否选中了单选按钮时,该 if 语句下的 d 代码不执行。 aspx 代码:

<ItemTemplate>
            <asp:Literal ID="Literal1" runat="server" Text='<%#Eval("ques") %>'></asp:Literal><br />
            <asp:RadioButton GroupName="a" ID="RadioButton1" Text='<%#Eval("ch1") %>' runat="server" /><br />
            <asp:RadioButton GroupName="a" ID="RadioButton2" Text='<%#Eval("ch2") %>' runat="server" /><br />
            <asp:RadioButton GroupName="a" ID="RadioButton3" Text='<%#Eval("ch3") %>' runat="server" /><br />
            <asp:RadioButton GroupName="a" ID="RadioButton4" Text='<%#Eval("ch4") %>' runat="server" /><br />

            <asp:Label ID="Label1" runat="server" Text='<%#Eval("ans") %>' Visible="false"></asp:Label><br />
            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label><br />
        </ItemTemplate>

后面的代码:

protected void Button1_Click(object sender, EventArgs e)
    {
        int count = 0;

        foreach(RepeaterItem Items in Repeater1.Items)
        {

            RadioButton r1 = (RadioButton)Items.FindControl("RadioButton1");
            RadioButton r2 = (RadioButton)Items.FindControl("RadioButton2");
            RadioButton r3 = (RadioButton)Items.FindControl("RadioButton3");
            RadioButton r4 = (RadioButton)Items.FindControl("RadioButton4");
            Label l3 = (Label)Items.FindControl("Label3");

            Label l=(Label)Items.FindControl("Label1");
            l3.Text = "hello?";
            if (r1.Checked)
            {
               if(r1.Text==l.Text)
                     count++;
            }
            else
            {
                if (r2.Checked)
                {
                    if(r2.Text==l.Text)
                       count++;
                }
            }
              // and so on for all 4 options
        }
        Label2.Visible = true;
        Label2.Text = "your score is " + count;       //always zero!

    }

【问题讨论】:

    标签: asp.net radio-button repeater


    【解决方案1】:

    如果您正在单步调试调试器,并且您的行

    if(r1.Text==l.Text) 
      count++; 
    

    没有执行,那么我猜if (r1.Checked) 行的评估结果为假。

    在此页面的 Page_Load() 方法中,这些单选按钮是否有任何数据绑定或操作?如果是这样,除非您将它们包装在 if(!Page.IsPostBack){ ... } 条件中,否则它将清除用户对单选按钮所做的任何事情,因此 r1.Checked 将是 false

    我希望这可能会有所帮助 :) 祝你好运。

    【讨论】:

      【解决方案2】:

      您需要执行以下操作:

      1. 将单选按钮控件上的AutoPostBack 设置为true。
      2. 将转发器控件上的OnItemCommand 设置为“Button1_Click”
      3. 将 Button1_Click 方法的签名更改为protected void Button1_Click(object sender, RepeaterCommandEventArgs e)

      这至少会触发你代码中的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-08
        • 2016-09-26
        • 2012-03-07
        • 1970-01-01
        • 2014-04-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        相关资源
        最近更新 更多