Here i have added Custom Validation also so that user have attempt all the questions.
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="Script/jquery-1.10.2.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(':radio').click(function () {
var rowindex = $(this).closest("tr")[0].rowIndex;
var mainRowindex = $(this).parent().parent().parent().parent().parent().parent()[0].rowIndex;
$('#tbQuestion tr:eq(' + mainRowindex + ') td:eq(' + (rowindex + 1) + ')').find(':radio').attr('checked', 'checked');
});
});
function ValidateRadio(sender, args) {
var tab = $(sender).parent().parent().parent().parent();
var radiobutton = tab.find('input[type=radio]');
debugger;
var count = 0;
for (var i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
count++;
}
}
if (count == 0) {
args.IsValid = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:DataList ID="dlQuestion" runat="server" DataKeyField="QuestionId">
<ItemTemplate>
<p>
<%#Container.ItemIndex+1 %>
)
<%# Eval("QuestionDescription")%>
</p>
<table>
<tr>
<td>
<asp:RadioButton ID="rblOptionOne" GroupName="Questions" Text='<%# Eval("OptionOne") %>'
runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rblOptionTwo" GroupName="Questions" Text='<%# Eval("OptionTwo") %>'
runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rblOptionThree" GroupName="Questions" Text='<%# Eval("OptionThree") %>'
runat="server" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rblOptionFour" GroupName="Questions" Text='<%# Eval("OptionFour") %>'
runat="server" />
</td>
<td>
<asp:CustomValidator ID="CustomValidator1" runat="server" ValidationGroup="Group"
ErrorMessage="Please Select" ClientValidationFunction="ValidateRadio"></asp:CustomValidator>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</td>
<td valign="top" align="right" style="width: 500px">
<h2>
Your answer
</h2>
<table id="tbQuestion">
<asp:Repeater ID="rptAnswer" runat="server">
<ItemTemplate>
<tr>
<td>
<itemtemplate>
<%#Container.ItemIndex+1 %>
</itemtemplate>
</td>
<td>
<asp:RadioButton ID="rblOptionOne" runat="server" GroupName="Answer" />
</td>
<td>
<asp:RadioButton ID="rblOptionTwo" runat="server" GroupName="Answer" />
</td>
<td>
<asp:RadioButton ID="rblOptionThree" runat="server" GroupName="Answer" />
</td>
<td>
<asp:RadioButton ID="rblOptionFour" runat="server" GroupName="Answer" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" Text="Submit" OnClick="Submit" ValidationGroup="Group" runat="server" />
</form>
</body>
</html>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.Populate();
}
}
private void Populate()
{
string constr = ConfigurationManager.ConnectionStrings["ConString2"].ConnectionString;
using (SqlConnection _cn = new SqlConnection(constr))
{
using (SqlCommand _cmd = new SqlCommand("SELECT * FROM QuestionTable", _cn))
{
using (SqlDataAdapter da = new SqlDataAdapter(_cmd))
{
_cn.Open();
DataSet ds = new DataSet();
da.Fill(ds);
dlQuestion.DataSource = ds;
dlQuestion.DataBind();
ViewState["ds"] = ds;
this.rptAnswer.DataSource = ds;
this.rptAnswer.DataBind();
_cn.Close();
}
}
}
}
protected void Submit(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("CorrectAnswer", typeof(string));
foreach (DataListItem item in dlQuestion.Items)
{
int index = Convert.ToInt32(dlQuestion.DataKeys[item.ItemIndex]);
bool a = (item.FindControl("rblOptionOne") as RadioButton).Checked;
bool b = (item.FindControl("rblOptionTwo") as RadioButton).Checked;
bool c = (item.FindControl("rblOptionThree") as RadioButton).Checked;
bool d = (item.FindControl("rblOptionFour") as RadioButton).Checked;
string answer = string.Empty;
if (a)
{
answer = "OptionOne";
}
else if (b)
{
answer = "OptionTwo";
}
else if (c)
{
answer = "OptionThree";
}
else
{
answer = "OptionFour";
}
dt.Rows.Add(answer);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
DataSet question = (DataSet)ViewState["ds"];
int correctCount = 0;
int wrongCount = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["CorrectAnswer"].ToString().ToUpper() == question.Tables[0].Rows[i]["CorrectAnswer"].ToString().ToUpper())
{
correctCount++;
}
else
{
wrongCount++;
}
}
string message = string.Format("Correct One: {0}. Wrong One: {1}", correctCount.ToString(), wrongCount.ToString());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
if you want to store the answer also then you can save the data row by row in table after that get rows from two table for which they are having same CorrectAnswers. Like this.
C#:
protected void Submit(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("CorrectAnswer", typeof(string));
foreach (DataListItem item in dlQuestion.Items)
{
int index = Convert.ToInt32(dlQuestion.DataKeys[item.ItemIndex]);
bool a = (item.FindControl("rblOptionOne") as RadioButton).Checked;
bool b = (item.FindControl("rblOptionTwo") as RadioButton).Checked;
bool c = (item.FindControl("rblOptionThree") as RadioButton).Checked;
bool d = (item.FindControl("rblOptionFour") as RadioButton).Checked;
string answer = string.Empty;
if (a)
{
answer = "OptionOne";
}
else if (b)
{
answer = "OptionTwo";
}
else if (c)
{
answer = "OptionThree";
}
else
{
answer = "OptionFour";
}
this.AddAnswers(index, answer);
}
this.GetTotalAnswer();
}
private void AddAnswers( int questionId,string answers)
{
// Write here inssert query to store answers in answer table not in Question table
}
private void GetTotalAnswer()
{
// Get the numberes of answers
// Selected QuestionId from AnswerTable and QuestionTable both table columns CorrectAnswer are same
//Depending on Row count display the result
}
SQL:
CREATE TABLE [dbo].[QuestionTable](
[QuestionId] [int] IDENTITY(1,1) NOT NULL,
[QuestionDescription] [varchar](max) NOT NULL,
[OptionOne] [varchar](30) NOT NULL,
[OptionTwo] [varchar](30) NOT NULL,
[OptionThree] [varchar](30) NOT NULL,
[OptionFour] [varchar](30) NOT NULL,
[CorrectAnswer] [varchar](20) NOT NULL,
CONSTRAINT [PK_QuestionTable] PRIMARY KEY CLUSTERED
(
[QuestionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Store answers as OptionOne,OptionTwo in CorrectAnswer column.
Please follow the steps and solved your problem.