如何在datalist中获取选定的单选按钮文本?

时间:2012-04-07 05:40:28

标签: c# javascript asp.net

在下面的数据列表中表示问题和答案的集合,当用户使用javascript点击提交按钮时,如何检查用户是否选择了正确答案单选按钮?

答案存储在数据库中。

Datalist中:

<asp:DataList ID="DataList1" runat="server" DataKeyField="Qno" 
        DataSourceID="SqlDataSource1">
        <ItemTemplate>
            Qno:
            <asp:Label ID="QnoLabel" runat="server" Text='<%# Eval("Qno") %>' />
            <br />
            Question:
            <asp:Label ID="QuestionLabel" runat="server" Text='<%# Eval("Question") %>' />
            <br />
            <asp:RadioButton ID="RadioButton1" runat="server" Text='<%# Eval("Ans1") %>' />
            <br />
            <asp:RadioButton ID="RadioButton2" runat="server" Text='<%# Eval("Ans2") %>' />
            <br />
            <asp:RadioButton ID="RadioButton3" runat="server" Text='<%# Eval("Ans3") %>' />
            <br />
            <asp:RadioButton ID="RadioButton4" runat="server" Text='<%# Eval("Ans4") %>' />
            <br />
            <asp:Button ID="Button2" runat="server" Text="Submit" />
            <br />
        </ItemTemplate>
    </asp:DataList>

1 个答案:

答案 0 :(得分:0)

为DataList中的Button2提供CommandName参数: CommandName =“Validate”

为DataList1添加OnItemCommand事件:* OnItemCommand =“DataList1_OnItemCommand”*

在后面的代码中,填写* DataList1_OnItemCommand *事件动作:

protected void DataList1_OnItemCommand(object sender, DataListCommandEventArgs e)
{
 if (String.Equals(e.CommandName, "Validate"))
 {
  DataListItem dataItem = (DataListItem )e.Item;
  RadioButton rbtn1 = (RadioButton)dataItem.FindControl("RadioButton1");
  RadioButton rbtn2 = (RadioButton)dataItem.FindControl("RadioButton2");
  RadioButton rbtn3 = (RadioButton)dataItem.FindControl("RadioButton3");
  RadioButton rbtn4 = (RadioButton)dataItem.FindControl("RadioButton4");

  // Code to check which radio button was checked.
  if(rbtn1 != null && rbtn1.Checked)
  {

  }
  else if(rbtn2 != null && rbtn2.Checked)
  {

  } //Perform these for the remaining two check boxes
 }
}

根据选中的复选框采取必要的操作。