当我尝试检查单选按钮是否被选中时,代码不会执行

时间:2012-01-04 10:16:50

标签: asp.net radio-button repeater

我正在尝试2在asp.net中进行测验。 使用单选按钮显示mcq选项r。在代码背后,当我尝试2检查是否检查radiobutton时,在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!

    }

2 个答案:

答案 0 :(得分:1)

如果您正在逐步调试调试器和行

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

没有执行,那么我猜测行if (r1.Checked)正在评估为假。

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

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

答案 1 :(得分:0)

您需要执行以下操作:

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