Implement Question Answer (Quiz) with Paging using Repeater control in ASP.Net

Kibock
 
on Oct 14, 2019 01:02 AM
Sample_933657.zip
1545 Views

Dear All,

I would like to implement paging using ArrayList and based on total record in database. In this case maximum 5 questions per page:

http://www.kystregister.no/ArraylistRadioBtn.jpg

I am using the following code snippet:

<tr>
    <td>
        <asp:Panel ID="Panel1" runat="server" ClientIDMode="Static" Visible="False">
        </asp:Panel>
    </td>
</tr>

 

    StringBuilder htmlTable = new StringBuilder();
    ArrayList ans = new ArrayList();
    int cm;
    int nm, tm,pp;
    string sid;
    protected void Page_Load(object sender, EventArgs e)
    {           
          if (Session["un"] == null)
        {
            Response.Redirect("login.aspx");
        }          
        
        sid = Request["sid"];
        SqlConnection myconn;
        SqlCommand mycomm;
        myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        myconn.Open();
        mycomm = new SqlCommand("select correctmarks,negativemarks,passp from addsubject where subjectid=@a", myconn);
        mycomm.Parameters.AddWithValue("@a", sid);
        SqlDataReader myreader;
        myreader = mycomm.ExecuteReader();
        myreader.Read();
        cm = Convert.ToInt32(myreader[0].ToString());
        nm = Convert.ToInt32(myreader[1].ToString());
        pp = Convert.ToInt32(myreader[2].ToString());
        myreader.Close();

        mycomm = new SqlCommand("select * from question where subjectid=@a", myconn);
        mycomm.Parameters.AddWithValue("@a", sid);

        int x = 1;
        myreader = mycomm.ExecuteReader();
        while (myreader.Read())
        {
            RadioButtonList myrblist = new RadioButtonList();
            Label mylabel = new Label();

            mylabel.ID = "Label" + x.ToString();
            myrblist.ID = "RadioButtonList" + x.ToString();
            myrblist.Items.Add(myreader["op1"].ToString());
            myrblist.Items.Add(myreader["op2"].ToString());
            myrblist.Items.Add(myreader["op3"].ToString());
            myrblist.Items.Add(myreader["op4"].ToString());
            ans.Add(myreader["ans"].ToString());

            mylabel.Text = "Question " + x.ToString() + ":- " + myreader["quename"].ToString();
            Panel1.Controls.Add(mylabel);
            Panel1.Controls.Add(myrblist);
            x++;
        }
        tm = (x-1) * cm;
        myconn.Close();
        if (Page.IsPostBack == false)
        {      
            Panel1.Visible = true;
            Panel3.Visible = true;
            int ttime = (x * 60) - 60;
            htmlTable.Append("<script> var seconds = " + ttime + "; function secondPassed() { var minutes = Math.round((seconds - 30) / 60); var remainingSeconds = seconds % 60; if (remainingSeconds < 10) { remainingSeconds = '0' + remainingSeconds;  } document.getElementById('countdown').innerHTML = 'Time Left :- ' + minutes + ':' + remainingSeconds; if (seconds == 0) { clearInterval(countdownTimer);document.getElementById('Button1').click(); } else  { seconds--; } } var countdownTimer = setInterval('secondPassed()', 1000);</script>");
            PlaceHolder1.Controls.Add(new Literal { Text = htmlTable.ToString() });
        }
    }

Many thanks in advance

Download FREE API for Word, Excel and PDF in ASP.Net: Download
pandeyism
 
on Oct 15, 2019 06:48 AM

Hi Kibock,

Refer below sample.

Database

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]

SQL Query

ALTER PROCEDURE GetQuestionPageWise
      @PageIndex INT = 1
      ,@PageSize INT = 10
      ,@RecordCount INT OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
      (
            ORDER BY [QuestionId] ASC
      )AS RowNumber
      ,[QuestionId]
      ,[QuestionDescription]
      ,[OptionOne]
      ,[OptionTwo]
      ,[OptionThree]
      ,[OptionFour]
     INTO #Results
      FROM QuestionTable
     
      SELECT @RecordCount = COUNT(*)
      FROM #Results
           
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
     
      DROP TABLE #Results
END
GO

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        .Repeater, .Repeater td, .Repeater td
        {
            border: 1px solid #ccc;
        }
        .Repeater td
        {
            background-color: #eee !important;
        }
        .Repeater th
        {
            background-color: #6C6C6C !important;
            color: White;
            font-size: 10pt;
            line-height: 200%;
        }
        .Repeater span
        {
            color: black;
            font-size: 10pt;
            line-height: 200%;
        }
        .page_enabled, .page_disabled
        {
            display: inline-block;
            height: 20px;
            min-width: 20px;
            line-height: 20px;
            text-align: center;
            text-decoration: none;
            border: 1px solid #ccc;
        }
        .page_enabled
        {
            background-color: #eee;
            color: #000;
        }
        .page_disabled
        {
            background-color: #6C6C6C;
            color: #fff !important;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater runat="server" ID="rptQuiz" OnItemDataBound="rptQuiz_ItemDataBound">
            <ItemTemplate>
                <div>
                    <h1>
                        <asp:Label ID="lblQuestion" Text='<%#Eval("QuestionDescription") %>' runat="server" />
                        <asp:HiddenField runat="server" Value='<%#Eval("QuestionId") %>' ID="hfQId" />
                    </h1>
                </div>
                <div>
                    <br />
                    <asp:RadioButtonList ID="rbtnOptions" runat="server">
                    </asp:RadioButtonList>
                    <br />
                    <br />
                </div>
            </ItemTemplate>
        </asp:Repeater>
        <asp:Repeater ID="rptPager" runat="server">
            <ItemTemplate>
                <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
                    CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
                    OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

Namespaces

C#

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration

Code

C#

private int PageSize = 2;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = GetCustomersPageWise(1);
        rptQuiz.DataSource = dt;
        rptQuiz.DataBind();
    }
}

protected void rptQuiz_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataTable DataTableQuestions;
        if (ViewState["Index"] != null)
        {

            int pageIndex = Convert.ToInt32(ViewState["Index"]);
            DataTableQuestions = GetCustomersPageWise(pageIndex);
        }
        else
        {
            DataTableQuestions = GetCustomersPageWise(1);
        }
        int id = Convert.ToInt32((e.Item.FindControl("hfQId") as HiddenField).Value);
        RadioButtonList rbtnOptions = e.Item.FindControl("rbtnOptions") as RadioButtonList;
        DataTable dt = DataTableQuestions.Select("QuestionId =" + id + "").CopyToDataTable();
        ListItem option1 = new ListItem(dt.Rows[0]["OptionOne"].ToString(), "0");
        ListItem option2 = new ListItem(dt.Rows[0]["OptionTwo"].ToString(), "1");
        ListItem option3 = new ListItem(dt.Rows[0]["OptionThree"].ToString(), "2");
        ListItem option4 = new ListItem(dt.Rows[0]["OptionFour"].ToString(), "3");
        rbtnOptions.Items.AddRange(new ListItem[4] { option1, option2, option3, option4 });
        rbtnOptions.DataBind();
    }
}

protected void Page_Changed(object sender, EventArgs e)
{
    int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
    ViewState["Index"] = pageIndex;
    this.GetCustomersPageWise(pageIndex);
    DataTable dt = this.GetCustomersPageWise(pageIndex);
    rptQuiz.DataSource = dt;
    rptQuiz.DataBind();
}

private DataTable GetCustomersPageWise(int pageIndex)
{
    string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("GetQuestionPageWise", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
            cmd.Parameters.AddWithValue("@PageSize", PageSize);
            cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
            cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
            this.PopulatePager(recordCount, pageIndex);
            return dt;
        }
    }
}

private void PopulatePager(int recordCount, int currentPage)
{
    double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
    int pageCount = (int)Math.Ceiling(dblPageCount);
    List<ListItem> pages = new List<ListItem>();
    if (pageCount > 0)
    {
        for (int i = 1; i <= pageCount; i++)
        {
            pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
        }
    }
    rptPager.DataSource = pages;
    rptPager.DataBind();
}

VB.Net

Private PageSize As Integer = 2
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Me.IsPostBack Then
        Dim dt As DataTable = GetCustomersPageWise(1)
        rptQuiz.DataSource = dt
        rptQuiz.DataBind()
    End If
End Sub

Protected Sub rptQuiz_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
        Dim DataTableQuestions As DataTable

        If ViewState("Index") IsNot Nothing Then
            Dim pageIndex As Integer = Convert.ToInt32(ViewState("Index"))
            DataTableQuestions = GetCustomersPageWise(pageIndex)
        Else
            DataTableQuestions = GetCustomersPageWise(1)
        End If

        Dim id As Integer = Convert.ToInt32((TryCast(e.Item.FindControl("hfQId"), HiddenField)).Value)
        Dim rbtnOptions As RadioButtonList = TryCast(e.Item.FindControl("rbtnOptions"), RadioButtonList)
        Dim dt As DataTable = DataTableQuestions.[Select]("QuestionId =" & id & "").CopyToDataTable()
        Dim option1 As ListItem = New ListItem(dt.Rows(0)("OptionOne").ToString(), "0")
        Dim option2 As ListItem = New ListItem(dt.Rows(0)("OptionTwo").ToString(), "1")
        Dim option3 As ListItem = New ListItem(dt.Rows(0)("OptionThree").ToString(), "2")
        Dim option4 As ListItem = New ListItem(dt.Rows(0)("OptionFour").ToString(), "3")
        rbtnOptions.Items.AddRange(New ListItem(3) {option1, option2, option3, option4})
        rbtnOptions.DataBind()
    End If
End Sub

Protected Sub Page_Changed(ByVal sender As Object, ByVal e As EventArgs)
    Dim pageIndex As Integer = Integer.Parse((TryCast(sender, LinkButton)).CommandArgument)
    ViewState("Index") = pageIndex
    Me.GetCustomersPageWise(pageIndex)
    Dim dt As DataTable = Me.GetCustomersPageWise(pageIndex)
    rptQuiz.DataSource = dt
    rptQuiz.DataBind()
End Sub

Private Function GetCustomersPageWise(ByVal pageIndex As Integer) As DataTable
    Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constring)
        Using cmd As SqlCommand = New SqlCommand("GetQuestionPageWise", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@PageIndex", pageIndex)
            cmd.Parameters.AddWithValue("@PageSize", PageSize)
            cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4)
            cmd.Parameters("@RecordCount").Direction = ParameterDirection.Output
            Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
            Dim dt As DataTable = New DataTable()
            da.Fill(dt)
            Dim recordCount As Integer = Convert.ToInt32(cmd.Parameters("@RecordCount").Value)
            Me.PopulatePager(recordCount, pageIndex)
            Return dt
        End Using
    End Using
End Function

Private Sub PopulatePager(ByVal recordCount As Integer, ByVal currentPage As Integer)
    Dim dblPageCount As Double = CDbl((CDec(recordCount) / Convert.ToDecimal(PageSize)))
    Dim pageCount As Integer = CInt(Math.Ceiling(dblPageCount))
    Dim pages As List(Of ListItem) = New List(Of ListItem)()

    If pageCount > 0 Then
        For i As Integer = 1 To pageCount
            pages.Add(New ListItem(i.ToString(), i.ToString(), i <> currentPage))
        Next
    End If

    rptPager.DataSource = pages
    rptPager.DataBind()
End Sub

Screenshot