前臺代碼: 後臺代碼: 遍歷gridview的每一行,取得RadioButton的值。 ...
前臺代碼:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" EmptyDataText="暫無試題" Width="100%" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:Label id="Label24" runat="server" Text="一、單選題(每題1分)"> </asp:Label> </HeaderTemplate> <ItemTemplate> <table id="Table2" cellSpacing="1" cellPadding="1" width="100%" align="center" border="0"> <tr> <td colSpan="4"> <asp:Label id="Label1" runat="server" Text='<%# Container.DataItemIndex+1 %>'> </asp:Label> <asp:Label id="Label2" runat="server" Text='<%# Eval("content","、{0}") %>'> </asp:Label> <asp:Label id="Label3" runat="server" Text='<%# Eval("answer") %>' Visible="False"> </asp:Label> <asp:Label id="Label4" runat="server" Text='<%# Eval("ID") %>' Visible="False"> </asp:Label> </td> </tr> <tr> <td width="35%"> <asp:RadioButton id="rbA" runat="server" Text='<%# Eval("answerA") %>' GroupName="Sl"> </asp:RadioButton></td> <td width="35%"> <asp:RadioButton id="rbB" runat="server" Text='<%# Eval("answerB") %>' GroupName="Sl"> </asp:RadioButton></td> <td></td> </tr> <tr> <td width="35%"> <asp:RadioButton id="rbC" runat="server" Text='<%# Eval("answerC") %>' GroupName="Sl"> </asp:RadioButton></td> <td width="35%"> <asp:RadioButton id="rbD" runat="server" Text='<%# Eval("answerD") %>' GroupName="Sl"> </asp:RadioButton></td> <td></td> </tr> </table> </ItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle Font-Size="12pt" HorizontalAlign="Left" /> </asp:GridView>
後臺代碼:
遍歷gridview的每一行,取得RadioButton的值。
/// <summary> /// 提交按鈕 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnCommit_Click(object sender, EventArgs e) { ItemOperater io = new ItemOperater(Session); int singlemark = 1;//取出單選題的每題分值 foreach (GridViewRow dr in GridView1.Rows)//對單選題每題進行判斷用戶選擇答案 { SelectedItem si = new SelectedItem(); string str = ""; if (((RadioButton)dr.FindControl("rbA")).Checked) { str = "A"; } else if (((RadioButton)dr.FindControl("rbB")).Checked) { str = "B"; } else if (((RadioButton)dr.FindControl("rbC")).Checked) { str = "C"; } else if (((RadioButton)dr.FindControl("rbD")).Checked) { str = "D"; } if (((Label)dr.FindControl("Label3")).Text.Trim() == str)//將用戶選擇結果和答案進行比較 { score = score + singlemark; } si.selected = str; //選中的答案 Label lbAnswer = (Label)dr.FindControl("Label3"); Label lbID = (Label)dr.FindControl("Label4"); si.answer = lbAnswer.Text.Trim(); si.ID = Convert.ToInt32(lbID.Text.Trim()); io.Add(si); } insert(io); //加到資料庫 lbScore.Text = score+""; } public void insert(ItemOperater io) { int stu_id=-1; if (Request["course_id"] != null) { course_id = Int32.Parse(Request["course_id"].ToString()); } stu_id = Convert.ToInt32(Session["ID"].ToString()); io.InsertScore(stu_id, score, course_id); }