5 Apr 2017

Online examination system project In Asp.Net with c#, SQL Database including Admin Panel - Download Part 2



QuestionsEntry.aspx.cs page code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Drawing;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
using System.Data.OleDb;



namespace OnlineExam
{
    public partial class QuestionsEntry : System.Web.UI.Page
    {
        OleDbConnection Econ; string constr, Query, sqlconn; 
        #region Declarations
        General clsGeneral = new General();
        string id = String.Empty;
        SqlCommand cmd, cmd1;
        SqlDataAdapter adp, adp3;
        DataSet ds, ds3;
       
        string fileName = string.Empty;
        string filePath = string.Empty;
        string getPath = string.Empty;
        string pathToStore = string.Empty;
        byte[] file3 = new byte[36871];
        string cat = "", sub = "";
        string PostId;
        int count;
        #endregion
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        private void WriteLog(string strError)
        {
            try
            {
                string AppPath = AppDomain.CurrentDomain.BaseDirectory;
                string strLog = @"LOG1\";
                string strFilePath = AppPath + strLog;

                if (!(Directory.Exists(strFilePath)))
                {
                    Directory.CreateDirectory(strFilePath);
                }
                string fn = string.Format("{0}{1}.txt", strFilePath, DateTime.Now.ToString("ddMMyyyy"));
                FileStream fs = new FileStream(fn, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter writer = new StreamWriter(fs);
                writer.WriteLine(string.Format("[ {0} ] {1}"DateTime.Now.ToString("HH:mm:ss"), strError));
                writer.Close();
                fs.Close();
            }
            finally
            {
                //nothing
            }


        }
        #region Page_Load
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
              
                if (!IsPostBack)
                {
                    if (Session["uid"] == null)
                    {
                        Response.Redirect("Login.aspx");
                    }
                    else
                    {
                        bindSubject();

                        lblresult.Text = "";
                        try
                        {
                           
                            if ((!string.IsNullOrEmpty(Request.QueryString["qid"])))
                            {
                                FillData();
                                BtnBatchsave.Text = "update";
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLog(ex.Message);
                        }
                    }
                  

                }

              


            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
        #endregion
        private void ExcelConn(string FilePath)
        {

            constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
            Econ = new OleDbConnection(constr);

        }
        private void connection()
        {
            sqlconn = ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString;
            con = new SqlConnection(sqlconn);

        } 
        private void InsertExcelRecords(string FilePath)
        {
            ExcelConn(FilePath);

            Query = string.Format("Select [sid],[question],[option1],[option2],[option3],[option4],[cans] FROM [{0}]""Sheet1$");
            OleDbCommand Ecom = new OleDbCommand(Query, Econ);
            Econ.Open();

            DataSet ds = new DataSet();
            OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
            Econ.Close();
            oda.Fill(ds);
            DataTable Exceldt = ds.Tables[0];
            connection();
            //creating object of SqlBulkCopy   
            SqlBulkCopy objbulk = new SqlBulkCopy(con);
            //assigning Destination table name   
            objbulk.DestinationTableName = "Questions";
            //Mapping Table column   
            objbulk.ColumnMappings.Add("sid""sid");
            objbulk.ColumnMappings.Add("question""question");
            objbulk.ColumnMappings.Add("option1""option1");
            objbulk.ColumnMappings.Add("option2""option2");
            objbulk.ColumnMappings.Add("option3""option3");
            objbulk.ColumnMappings.Add("option4""option4");
            objbulk.ColumnMappings.Add("cans""cans");
            //inserting Datatable Records to DataBase   
            con.Open();
            objbulk.WriteToServer(Exceldt);
            con.Close();
            ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "alertMessage""alert('Excel Questions Uploaded succesfully')"true);

        } 
   

        private void bindSubject()
        {
            try
            {
                adp = new SqlDataAdapter("select sid,sname  from Subjects order by sname", con);
                ds = new DataSet();
                adp.Fill(ds);
                ddlSub.DataSource = ds;
                ddlSub.DataTextField = "sname";
                ddlSub.DataValueField = "sid";
                ddlSub.DataBind();
                ddlSub.Items.Insert(0, "--Select--");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }

        public void FillData()
        {
            try
            {
                adp = new SqlDataAdapter("SELECT * FROM Questions WHERE qid= '" + Request.QueryString["qid"].ToString() + "' ", con);
                ds = new DataSet();
                adp.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {

                  
                    txtOption1.Text = ds.Tables[0].Rows[0]["option1"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["option1"].ToString();
                    txtOption2.Text = ds.Tables[0].Rows[0]["option2"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["option2"].ToString();
                    txtOption3.Text = ds.Tables[0].Rows[0]["option3"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["option3"].ToString();
                    txtOption4.Text = ds.Tables[0].Rows[0]["option4"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["option4"].ToString();

                   // txtMetaKey.Text = ds.Tables[0].Rows[0]["cans"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["cans"].ToString();

                    txtQuestion.Text = ds.Tables[0].Rows[0]["question"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["question"].ToString();
                    if (ds.Tables[0].Rows[0]["cans"] != DBNull.Value)
                    {
                        rbtAns.Items.FindByValue(ds.Tables[0].Rows[0]["cans"].ToString().Trim()).Selected = true;
                    }
                    bindSubject();
                    ddlSub.Items.FindByValue(ds.Tables[0].Rows[0]["sid"].ToString().Trim()).Selected = true;
                   
                }
                btnSave.Text = "update";
            }
            catch (Exception ex)
            {
                WriteLog("AddProperty.aspx--FillData()--" + Session["UserLog"].ToString() + "--" + ex.Message);
                throw ex;
            }
        }


        #region DisableTheButton
        public static string DisableTheButton(Control pge, Control btn)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("if (typeof(Page_ClientValidate) == 'function') {");
            sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
            sb.Append("this.value = 'Please wait...';");
            sb.Append("this.disabled = true;");
            sb.Append("this.hidden = true;");

            sb.Append(pge.Page.GetPostBackEventReference(btn));
            //sb.Append(pge.Page.GetPostBackEventReference(btn));
            sb.Append(";");
            return sb.ToString();
        }
        #endregion

        #region Check Coordinator
        /// <summary>
        /// This method is used for check the Placement Co-Ordinator Exist or not.
        /// </summary>
        /// <returns></returns>

        #endregion




        #region Clearing of controls
        /// <summary>
        /// This method is used for All Controls
        /// </summary>
        ///
        protected void clear()
        {
            lblresult.Text = "";
            Resetfromcontrol(this);        
            ddlSub.SelectedIndex = 0;

            BtnBatchsave.Text = "submit";
        }
        public void Resetfromcontrol(Control parent)
        {
            foreach (Control c in parent.Controls)
            {
                if (c.Controls.Count > 0)
                {
                    Resetfromcontrol(c);
                }
                else
                {
                    switch (c.GetType().ToString())
                    {
                        case "System.Web.UI.WebControls.TextBox":
                            ((TextBox)c).Text = "";
                            break;
                    }
                }
            }
        }
        #endregion

        #region Set_Tab
        protected void Set_Tab(TextBox Parm_TextBox_Current, TextBox Parm_TextBox_Next)
        {
            string MyCommand = "MoveToNextTab(this,event," + Parm_TextBox_Current.MaxLength + ",'" + Parm_TextBox_Next.ClientID + "')";
            Parm_TextBox_Current.Attributes.Add("onkeyup", MyCommand);
        }
        #endregion



        #region OnPreRender
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            StringBuilder javaScript = new StringBuilder();
            javaScript.Append("\n<script language=JavaScript>\n");
            javaScript.Append("window.history.forward(1);\n");
            javaScript.Append("</script>\n");
            Page.RegisterClientScriptBlock("HistoryScript", javaScript.ToString());
        }
        #endregion
   
        protected void BtnBatchsave_Click(object sender, EventArgs e)
        {
            int i = 0;
            try
            {

            if (BtnBatchsave.Text.ToLower() == "submit" && ddlSub.SelectedIndex != 0)
            {

                i = clsGeneral.insertQuestion(ddlSub.SelectedValue, txtQuestion.Text, txtOption1.Text, txtOption2.Text, txtOption3.Text, txtOption4.Text, rbtAns.SelectedValue, Session["uid"].ToString());
                    clear();

                    lblresult.Text = "<font color=green>Saved Successfully.</font>";
               
            }
            else if (BtnBatchsave.Text.ToLower() == "update" && ddlSub.SelectedIndex != 0)
            {

                i = clsGeneral.UpdateQuestion(Request.QueryString["qid"].ToString(), ddlSub.SelectedValue, txtQuestion.Text, txtOption1.Text, txtOption2.Text, txtOption3.Text, txtOption4.Text, rbtAns.SelectedValue, Session["uid"].ToString());
                clear();

                lblresult.Text = "<font color=green>Updated Successfully.</font>";
            }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
        protected void BtnbatchClear_Click(object sender, EventArgs e)
        {
            clear();

            BtnBatchsave.Text = "Submit";
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblDisplay.Visible = true;
            pnlEditor.Visible = false;
            lblDisplay.Text = txtQuestion.Text;
            btnSave.Visible = false;
            btnCancel.Visible = true;
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            lblDisplay.Visible = false;
            pnlEditor.Visible = true;
            lblDisplay.Text = "";
            txtQuestion.Text = "";
            btnSave.Visible = true;
            btnCancel.Visible = false;
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                string FilePath = "images/" + FileName;
                FileUpload1.SaveAs(Server.MapPath(FilePath));
                txtQuestion.Text += string.Format("<img src = '{0}' alt = '{1}' />", FilePath, FileName);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //string CurrentFilePath = Path.GetFullPath(FileUpload2.PostedFile.FileName);
           string CurrentFilePath = Server.MapPath("~/Files/") + FileUpload2.FileName;
            InsertExcelRecords(CurrentFilePath); 
        }

       
    }
}

 ======================================================================
Admin can Manage Questions page code

ViewQuestions.aspx page code
<%@ Page Title="" Language="C#" MasterPageFile="~/AdminMaster.Master" AutoEventWireup="true" CodeBehind="ViewQuestion.aspx.cs" Inherits="OnlineExam.ViewQuestion" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


    <div class="row">
        <div class="col-lg-12">
            <h4> View Questions </h4>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <table border="0" cellpadding="0" cellspacing="0" class="table table-striped table-bordered table-hover"
            align="center" style="width: 1189px; height: 795px;">
            <tr>
                <td>
               
            <asp:DropDownList ID="ddlshow" runat="server" AutoPostBack="True" class="form-control" Visible="false"
                                                TabIndex="1" Width="75px" OnSelectedIndexChanged="ddlshow_SelectedIndexChanged">
                                                <asp:ListItem Value="20">20</asp:ListItem>
                                                <asp:ListItem Value="50">50</asp:ListItem>
                                                <asp:ListItem Value="75">75</asp:ListItem>
                                                <asp:ListItem Value="100">100</asp:ListItem>
                                            </asp:DropDownList>

                                            Subject &nbsp;   <asp:DropDownList ID="ddlSub" class="form-control" runat="server" AutoPostBack="True"
                                                OnSelectedIndexChanged="ddlSub_SelectedIndexChanged" TabIndex="1" Width="160px">
                                                <asp:ListItem>--Select--</asp:ListItem>
                                            </asp:DropDownList>
                  <div class="box-body">
                  

                  <table class="table table-bordered">
                   <asp:GridView ID="grdProperties" runat="server" AutoGenerateColumns="False" ShowFooter="true"
                                                CellPadding="4" CssClass="table table-hover table-bordered" GridLines="None"
                                                Width="101%" Style="margin-right: 20px"
                                              OnRowCommand="grdProperties_RowCommand">                                              
                                                <RowStyle BackColor="#F5F5F5" />
                                                <AlternatingRowStyle BackColor="#FFFFFF" />
                                                <Columns>
                                                    

                                                     <asp:TemplateField HeaderText="Question" FooterText="Question" FooterStyle-Font-Bold="true">
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblqst" runat="server" Text='<%# Gethtml(Eval("question").ToString()) %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <FooterTemplate>
                                                            Question
                                                        </FooterTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Subject" FooterText="Subject" FooterStyle-Font-Bold="true">
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblctgry" runat="server" Text='<%# Eval("sname") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <FooterTemplate>
                                                            Subject
                                                        </FooterTemplate>
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="FID" Visible="false">
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblfid" runat="server" Text='<%# Eval("qid") %>'></asp:Label>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                  
                                                    <asp:TemplateField HeaderText="Edit" ShowHeader="False" FooterText="Edit" FooterStyle-Font-Bold="true">
                                                        <ItemTemplate>
                                                            <asp:LinkButton ID="lbtnedit" runat="server" CausesValidation="False" CommandName="wdcEdit"
                                                                CommandArgument='<%# Eval("qid") %>' Text="Edit"></asp:LinkButton>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                  
                                                </Columns>
                                                <EmptyDataTemplate>
                                                    <b>No records found</b>
                                                </EmptyDataTemplate>
                                            </asp:GridView>
                  </table>
                </div><!-- /.box-body -->
                <div class="box-footer clearfix">
                <div style="float:right;">
                     <table cellpadding="0" border="0">
                        <tr><td>
                                <asp:Label ID="lblPageInfo" runat="server" style="font-weight: 700" Visible="false"></asp:Label>
                           </td><td>&nbsp;&nbsp;</td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnFirst" runat="server"
                                    CausesValidation="false" OnClick="lbtnFirst_Click" CssClass="paging" Visible="false">First</asp:LinkButton>
                                &nbsp;</td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnPrevious" CssClass="paging" runat="server"
                                    CausesValidation="false" OnClick="lbtnPrevious_Click"><<</asp:LinkButton>&nbsp;&nbsp;</td>
                            <td >
                                <asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand"
                                    OnItemDataBound="dlPaging_ItemDataBound">
                                    <ItemTemplate>
                                        <asp:LinkButton  ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
                                            CommandName="Paging" Text='<%# Eval("PageText") %>'></asp:LinkButton>&nbsp;
                                    </ItemTemplate>
                                    <SeparatorTemplate>&nbsp;|&nbsp;</SeparatorTemplate>
                                </asp:DataList>
                            </td>
                            <td align="left">
                                &nbsp;&nbsp;<asp:LinkButton CssClass="paging" ID="lbtnNext" runat="server" CausesValidation="false"
                                    OnClick="lbtnNext_Click">>></asp:LinkButton></td>
                            <td align="left">
                                &nbsp;
                                <asp:LinkButton ID="lbtnLast" runat="server" Visible="false" CausesValidation="false" OnClick="lbtnLast_Click" CssClass="paging">Last</asp:LinkButton></td>
                                <td style="padding-left:5px;">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="7" align="center" style="display:none;" valign="middle">
                                &nbsp;</td>
                        </tr>
                    </table></div>
                </div>
               
                </td>
              </tr></table>
                 
                  
                     
                    
                
                                   
                    </div>
                   
  
</asp:Content>


 ========================================================================
ViewQuestions.aspx.cs page code
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
using System.Globalization;

namespace OnlineExam
{
    public partial class ViewQuestion : System.Web.UI.Page
    {
        #region Declaration
        General clsGeneral = new General();
        comFunctions fssFunctions = new comFunctions();
        SqlDataAdapter adp;
        DataSet ds, dsHelp;
        string strLogUser;
        int Result;
        #endregion
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ToString());
        #region Private Properties
        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;
                if (objPage == null)
                {
                    _CurrentPage = 0;
                }
                else
                {
                    _CurrentPage = (int)objPage;
                }
                return _CurrentPage;
            }
            set { ViewState["_CurrentPage"] = value; }
        }
        private int fistIndex
        {
            get
            {

                int _FirstIndex = 0;
                if (ViewState["_FirstIndex"] == null)
                {
                    _FirstIndex = 0;
                }
                else
                {
                    _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
                }
                return _FirstIndex;
            }
            set { ViewState["_FirstIndex"] = value; }
        }
        private int lastIndex
        {
            get
            {

                int _LastIndex = 0;
                if (ViewState["_LastIndex"] == null)
                {
                    _LastIndex = 0;
                }
                else
                {
                    _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
                }
                return _LastIndex;
            }
            set { ViewState["_LastIndex"] = value; }
        }
        #endregion
        #region PagedDataSource
        PagedDataSource _PageDataSource = new PagedDataSource();
        #endregion
        string lang = "";


        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["uid"]  == null)
            {
                ClientScriptManager csm = Page.ClientScript;
                csm.RegisterStartupScript(this.GetType(), "redirectlogin""<script  type='text/javascript' language='javascript'>parent.top.location.href='Login.aspx'; </script>");
                return;
            }
            try
            {
                string ConStr = ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString;
                cn = new SqlConnection(ConStr);
                if (cn.State == ConnectionState.Closed)
                {
                    cn.Open();
                }
                Page.MaintainScrollPositionOnPostBack = true;
               
                if (Page.IsPostBack == false)
                {
                    bindSubject();
                    BindQuestions();
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
                throw ex;
            }
        }
        private void bindSubject()
        {
            try
            {
                adp = new SqlDataAdapter("select sid,sname  from Subjects order by sname", cn);
                ds = new DataSet();
                adp.Fill(ds);
                ddlSub.DataSource = ds;
                ddlSub.DataTextField = "sname";
                ddlSub.DataValueField = "sid";
                ddlSub.DataBind();
                ddlSub.Items.Insert(0, "--Select--");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
        private bool WriteLog(string strError)
        {
            string AppPath = AppDomain.CurrentDomain.BaseDirectory;
            string strLog = @"LOG1\";
            string strFilePath = AppPath + strLog;

            if (!(Directory.Exists(strFilePath)))
            {
                Directory.CreateDirectory(strFilePath);
            }
            string fn = string.Format("{0}{1}.txt", strFilePath, DateTime.Now.ToString("ddMMyyyy"));
            FileStream fs = new FileStream(fn, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

            StreamWriter writer = new StreamWriter(fs);
            writer.Write("[ " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + " ]");
            writer.WriteLine(strError);
            writer.WriteLine("--------------------------------------------------------------------------");
            writer.Close();
            fs.Close();
            return true;
        }

        protected void ddlSub_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                BindQuestions();
            }
            catch (Exception ex)
            {
              
            }
        }
        protected string Gethtml(string sttdesc)
        {

            return Server.HtmlDecode(sttdesc);
        }
        private DataSet GetUpcomingProperty(string catid)
        {
            try
            {
                if (cn.State == ConnectionState.Closed) { cn.Open(); };
                SqlDataAdapter myDataAdapter;
                myDataAdapter = new SqlDataAdapter("SP_GetQuestions", cn);
                if (catid.Trim() == "" || catid.Trim() == null || catid.Trim() == "--Select--")
                    myDataAdapter.SelectCommand.Parameters.Add("@catid"SqlDbType.VarChar).Value = "%";
                else
                    myDataAdapter.SelectCommand.Parameters.Add("@catid"SqlDbType.VarChar).Value = catid.Trim();


            
                myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                dsHelp = new System.Data.DataSet();

                myDataAdapter.Fill(dsHelp); //helpus.CloseConnection();
                return dsHelp;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //helpus.CloseConnection();
            }
        }
        public void BindQuestions()
        {
            try
            {
                DataSet BindBatch = GetUpcomingProperty(ddlSub.SelectedValue);
                if (BindBatch.Tables[0].Rows.Count > 0)
                {
                    DataTable dataTable = BindBatch.Tables[0];
                    _PageDataSource.DataSource = dataTable.DefaultView;
                    _PageDataSource.AllowPaging = true;
                    _PageDataSource.PageSize = Convert.ToInt32(ddlshow.SelectedValue);
                    _PageDataSource.CurrentPageIndex = CurrentPage;
                    ViewState["TotalPages"] = _PageDataSource.PageCount;

                    //this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
                    this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
                    this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
                    this.grdProperties.DataSource = _PageDataSource;
                    this.grdProperties.DataBind();
                    grdProperties.Columns[1].ItemStyle.Width = 180;
                    grdProperties.Columns[3].ItemStyle.Width = 90;
                    grdProperties.Columns[4].ItemStyle.Width = 90;
                    grdProperties.Columns[5].ItemStyle.Width = 90;
                    this.doPaging();
                }
                else
                {
                    grdProperties.DataSource = null;
                    grdProperties.DataBind();
                }
            }
            catch (Exception ex)
            {
            }
        }
     
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindQuestions();
        }


        private void doPaging()
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("PageIndex");
                dt.Columns.Add("PageText");
                fistIndex = CurrentPage - 5;
                if (CurrentPage > 5)
                {
                    lastIndex = CurrentPage + 5;
                }
                else
                {
                    lastIndex = 10;
                }
                if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
                {
                    lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                    fistIndex = lastIndex - 10;
                }
                if (fistIndex < 0)
                {
                    fistIndex = 0;
                }
                for (int i = fistIndex; i < lastIndex; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = i;
                    dr[1] = i + 1;
                    dt.Rows.Add(dr);
                }
                this.dlPaging.DataSource = dt;
                this.dlPaging.DataBind();
            }
            catch (Exception ex)
            {
                WriteLog("ViewProperty.aspx--doPaging()--" + Session["UserLog"].ToString() + "--" + ex.Message);
                throw ex;
            }
        }

        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            this.BindQuestions();
        }
        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindQuestions();
        }
        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            this.BindQuestions();
        }
        protected void lbtnLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            this.BindQuestions();
        }
        protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("Paging"))
            {
                CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
                this.BindQuestions();
            }
        }
        protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType != ListItemType.Separator)
                {
                    LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
                    if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
                    {
                        lnkbtnPage.Enabled = false;
                        lnkbtnPage.Style.Add("fone-size""14px");
                        lnkbtnPage.Font.Bold = true;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("ViewProperty.aspx--dlPaging_ItemDataBound()--" + Session["UserLog"].ToString() + "--" + ex.Message);
                throw ex;
            }

        }




        protected void ddlshow_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindQuestions();
        }
        protected void ddlSubCat_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        protected void grdProperties_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {

              
                if (e.CommandName == "wdcEdit")
                {
                    int ID = Convert.ToInt32(e.CommandArgument);
                    Response.Redirect("QuestionsEntry.aspx?qid=" + ID);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}

 ========================================================================
Admin can create multiple exams using different subjects and different number of questions


ExamEntry.aspx page code
<%@ Page Title="" Language="C#" MasterPageFile="~/AdminMaster.Master" AutoEventWireup="true" CodeBehind="ExamEntry.aspx.cs" Inherits="OnlineExam.ExamEntry" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

<table>
    <tr>
        <th  align="left"colspan="2" style="font-family:Verdana; color:orange; font-size:medium">
          
             Create Exam :
     </th>
    </tr>
    <tr>
        <td align="right">
            <asp:Label  ID="lblUser" runat="server" Text="Exam Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtExam" runat="server" Width="266px"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td align="right">
            <span style="color: Red"></span>Number of questions:
        </td>
        <td align="left" style="height: 34px">
            <asp:TextBox ID="txtNumq" runat="server" Width="266px"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td align="right">
          Time in minutes:
        </td>
        <td align="left" style="width: 551px">
             <asp:TextBox ID="txtMin" runat="server" Width="266px"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td align="right" style="width: 195px">
            Questions per subject:
        </td>
        <td align="left" style="width: 551px">
         <asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
            AutoGenerateColumns="false" onrowcreated="Gridview1_RowCreated">
            <Columns>         
            <asp:TemplateField HeaderText="Subjuct">
                <ItemTemplate><asp:TextBox ID="txtid" runat="server" Visible="false" Text='<%# Eval("sid") %>'></asp:TextBox>
                    <asp:TextBox ID="txtSub" runat="server" Text='<%# Eval("sname") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Number of questions">
                <ItemTemplate>
                    <asp:TextBox ID="txtNoq" runat="server" Text='<%# Eval("noq") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>    
            </Columns>
        </asp:gridview>
         
        </td>
    </tr>
    <tr>
        <td align="right">
            <span style="color: Red">*</span>Start Date:
        </td>
        <td align="left" style="width: 551px">
        
               <asp:TextBox ID="GMDatePicker1" runat="server"  Width="160px" ></asp:TextBox>


              <cc1:CalendarExtender ID="abc" runat="server"
                                                                                            Format="dd-MM-yyyy" TargetControlID="GMDatePicker1">
                                                                                        </cc1:CalendarExtender>
        </td>
    </tr>
    <tr>
        <td align="right">
            <span style="color: Red">*</span>End Date:
        </td>
        <td align="left" style="width: 551px">
        

             <asp:TextBox ID="GMDatePicker2" runat="server"  Width="160px" ></asp:TextBox>


              <cc1:CalendarExtender ID="abc1" runat="server"
                                                                                            Format="dd-MM-yyyy" TargetControlID="GMDatePicker2">
                                                                                        </cc1:CalendarExtender>
        </td>
    </tr>

    <tr>
        <td>
           
        </td>
        <td><br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save"
            Width="77px" />
          <asp:Label ID="lblID" Visible="false" runat="server" Text="" ></asp:Label>   <asp:Label ID="lbl" runat="server" Text="" Font-Size="Medium" Font-Bold="true" ForeColor="red"></asp:Label></td>
    </tr>
     <tr>
        <td>
           
        </td>
        <td><br /> </td>
    </tr>
     <tr>
        <td colspan="2">
           
            <br />
         
             <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" ShowFooter="true"
                                                CellPadding="4" CssClass="table table-hover table-bordered" GridLines="None"
                                                Width="101%" Style="margin-right: 20px"
                                              OnRowCommand="GridView2_RowCommand">                                              
                                                <RowStyle BackColor="#F5F5F5" />
                                                <AlternatingRowStyle BackColor="#FFFFFF" />
                                                <Columns>
                                                    

                                                     <asp:TemplateField HeaderText="Exam Name" FooterText="Exam Name" FooterStyle-Font-Bold="true">
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblqst" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                                                        </ItemTemplate>
                                                        <FooterTemplate>
                                                            Exam Name
                                                        </FooterTemplate>
                                                    </asp:TemplateField>
                                                  
                                                    <asp:TemplateField HeaderText="FID" Visible="false">
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblfid" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                  
                                                    <asp:TemplateField HeaderText="Edit" ShowHeader="False" FooterText="Edit" FooterStyle-Font-Bold="true">
                                                        <ItemTemplate>
                                                            <asp:LinkButton ID="lbtnedit" runat="server" CausesValidation="False" CommandName="wdcEdit"
                                                                CommandArgument='<%# Eval("Id") %>' Text="Edit"></asp:LinkButton>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                   <asp:TemplateField HeaderText="Delete" ShowHeader="False" FooterText="Delete" FooterStyle-Font-Bold="true">
                                                        <ItemTemplate>
                                                            <asp:LinkButton ID="lbt1nedit" runat="server" CausesValidation="False" CommandName="wdDelete"
                                                                CommandArgument='<%# Eval("Id") %>' Text="Delete"></asp:LinkButton>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                </Columns>
                                                <EmptyDataTemplate>
                                                    <b>No records found</b>
                                                </EmptyDataTemplate>
                                            </asp:GridView>
        </td>
    </tr>
</table><br />
</asp:Content>

 ======================================================================
ExamEntry.aspx.cs page code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;

namespace OnlineExam
{
    public partial class ExamEntry : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        private void SetInitialRow()
        {

            SqlDataAdapter adp = new SqlDataAdapter("select sid ,sname, '' as noq from Subjects ", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ViewState["CurrentTable"] = ds.Tables[0];
                Gridview1.DataSource = ds.Tables[0];
                Gridview1.DataBind();
            }

        }




        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SetInitialRow();
                Bind();
            }
        }
        private void Bind()
        {

            SqlDataAdapter adp = new SqlDataAdapter("select * from ExamMaster ", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {

                GridView2.DataSource = ds.Tables[0];
                GridView2.DataBind();
            }
        }


      

        //A method that Inserts the records to the database
        private void InsertRecords(StringCollection sc)
        {
         
            StringBuilder sb = new StringBuilder(string.Empty);
            string[] splitItems = null;
            foreach (string item in sc)
            {
                splitItems = item.Split(",".ToCharArray());
                int j = Convert.ToInt32(splitItems[0]);
                SqlDataAdapter adp = new SqlDataAdapter("select ID from MultipleAddress where ID= '" + j + "'", con);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)

                {
                    sb.AppendFormat("Update MultipleAddress set Email= '" + splitItems[1] + "',Phone = '" + splitItems[2] + "', Address = '" + splitItems[3] + "' where ID = '" + j + "'  ;");

                }
                else
                {
                    const string sqlStatement = "INSERT INTO MultipleAddress (ID, Email, Phone,Address) VALUES";
                    if (item.Contains(","))
                    {
                        sb.AppendFormat("{0}('{1}','{2}','{3}', '{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
                    }
                }
            }

            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand(sb.ToString(), con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                con.Close();
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script""alert('Records Successfuly Saved!');"true);

            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Insert Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {
                con.Close();
            }
        }
        protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label l = (Label)e.Row.FindControl("Label1");
                if (l != null)
                {
                    string script = "window.open('Default.aspx');";
                    l.Attributes.Add("onclick", script);
                }
            }
        }
        private DateTime convertDateIndia(string datetoconvert)
        {
            DateTime dtParam;
            System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");

            try
            {
                dtParam = Convert.ToDateTime(datetoconvert.ToString(), enGB);
                return dtParam;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {


            }


        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Button1.Text == "Save")
            {
                int Gross = 0;
                if (Gridview1.Rows.Count > 0)
                {
                    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        if(string.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString()))
                        Gross = Gross + 0;
                        else
                        Gross = Gross + Convert.ToInt32(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString());

                    }

                }
                if (Gross == Convert.ToInt32(txtNumq.Text))
                {
                    StringBuilder sb = new StringBuilder();
                    string k;
                    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        //if(string.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString()))
                        if (string.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString()))
                        {
                            k = ((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString();
                            if (k == "")
                            {
                                k = "0";
                            }
                            sb.Append(k);
                        }
                        else {
                            k = ((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString();
                            sb.Append(k);
                        }
                        sb.Append(',');
                    }
                    if (sb.Length >= 1) sb.Length--;

                    StringBuilder sb1 = new StringBuilder();
                    string k1;
                    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        if (string.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtid")).Text.ToString()))
                        {
                            k1 = "0";
                            sb1.Append(k1);
                        }
                        else {
                            k1 = ((TextBox)Gridview1.Rows[i].FindControl("txtid")).Text.ToString();
                            sb1.Append(k1);
                        }
                        sb1.Append(',');
                    }
                    if (sb1.Length >= 1) sb1.Length--;

                    SqlCommand cmd = new SqlCommand("insert into ExamMaster(Name, noq, time, subjects, QuestDetails, start, EndDate) values('" + txtExam.Text + "', '" + txtNumq.Text + "','" + txtMin.Text + "','" + sb1.ToString() + "','" + sb.ToString() + "','" + convertDateIndia(GMDatePicker1.Text) + "', '" + convertDateIndia(GMDatePicker2.Text) + "')", con);
                    cmd.CommandType = CommandType.Text;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close(); Bind(); clear();
                    ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "alertMessage""alert('Exam Created Successfully')"true);
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script""alert('Please check number of questions table.');"true);
                }
            }
            if (Button1.Text == "Update")
            {
                int Gross = 0;
                if (Gridview1.Rows.Count > 0)
                {
                    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        if (String.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text))
                            Gross = Gross + 0;
                        else
                            Gross = Gross + Convert.ToInt32(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString());
                    }

                }
                if (Gross == Convert.ToInt32(txtNumq.Text))
                {
                    StringBuilder sb = new StringBuilder();
                    string k;
                    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        if (string.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString()))
                        {
                            k = ((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString();
                            if (k == "")
                            {
                                k = "0";
                            }
                            sb.Append(k);
                        }
                        else
                        {
                            k = ((TextBox)Gridview1.Rows[i].FindControl("txtNoq")).Text.ToString();
                            sb.Append(k);
                        }
                        sb.Append(',');
                    }
                    if (sb.Length >= 1) sb.Length--;

                    StringBuilder sb1 = new StringBuilder();
                    string k1;
                    for (int i = 0; i < Gridview1.Rows.Count; i++)
                    {
                        if (String.IsNullOrEmpty(((TextBox)Gridview1.Rows[i].FindControl("txtid")).Text))
                            sb1.Append("0");
                        else
                        {
                            k1 = ((TextBox)Gridview1.Rows[i].FindControl("txtid")).Text.ToString();
                            sb1.Append(k1);
                        }
                        sb1.Append(',');
                    }
                    if (sb1.Length >= 1) sb1.Length--;

                    SqlCommand cmd = new SqlCommand("update ExamMaster set Name ='" + txtExam.Text + "', noq =  '" + txtNumq.Text + "', time = '" + txtMin.Text + "', subjects = '" + sb1.ToString() + "', QuestDetails = '" + sb.ToString() + "', start = '" + convertDateIndia(GMDatePicker1.Text) + "', EndDate = '" + convertDateIndia(GMDatePicker2.Text) + "' where id = '" + lblID.Text + "'", con);
                    cmd.CommandType = CommandType.Text;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close(); Bind(); clear(); lblID.Text = "";
                    ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "alertMessage""alert('Exam Updated Successfully')"true);
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script""alert('Please check number of questions table.');"true);
                }
            }
        }
   
        private void clear()
        {
            SetInitialRow();
            txtExam.Text = "";
            txtNumq.Text = "";
            txtMin.Text = "";
            Button1.Text = "Save";
            GMDatePicker1.Text = "";
            GMDatePicker2.Text = "";

        }

        protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {


                if (e.CommandName == "wdcEdit")
                {int i=0, j =0;
                    int ID = Convert.ToInt32(e.CommandArgument);
                    SqlDataAdapter adp = new SqlDataAdapter("select * from ExamMaster where ID= '" + ID + "'", con);
                    DataSet ds = new DataSet();
                    adp.Fill(ds);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        txtExam.Text = ds.Tables[0].Rows[0]["Name"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["Name"].ToString();
                        txtNumq.Text = ds.Tables[0].Rows[0]["noq"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["noq"].ToString();
                        txtMin.Text = ds.Tables[0].Rows[0]["time"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["time"].ToString();
                        GMDatePicker1.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["start"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["start"].ToString()).ToString("dd-MM-yyyy");
                        GMDatePicker2.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["EndDate"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["EndDate"].ToString()).ToString("dd-MM-yyyy");
                        lblID.Text = ID.ToString();


                        string sc = ds.Tables[0].Rows[0]["subjects"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["subjects"].ToString();
                        string[] splitItems = null;
                        splitItems = sc.Split(",".ToCharArray());

                        string sc1 = ds.Tables[0].Rows[0]["QuestDetails"] == DBNull.Value ? "" : ds.Tables[0].Rows[0]["QuestDetails"].ToString();
                        string[] splitItems1 = null;
                        splitItems1 = sc1.Split(",".ToCharArray());

                        //string[] values = new string[10];
                        DataTable table = new DataTable();
                        table.Columns.Add("sname"Type.GetType("System.String"));
                        table.Columns.Add("noq"Type.GetType("System.String"));
                        table.Columns.Add("sid"Type.GetType("System.String"));
                        foreach (var value in splitItems)
                        {
                            SqlDataAdapter adp1 = new SqlDataAdapter("select sname from Subjects where sid='" + value  + "'", con);
                            DataSet ds1 = new DataSet();
                            adp1.Fill(ds1);

                            if (ds1.Tables[0].Rows.Count > 0)
                            {
                                DataRow row = table.NewRow();
                                row["sname"] = ds1.Tables[0].Rows[0]["sname"].ToString() ;
                                table.Rows.Add(row);
                            }
                        }
                        foreach (var value in splitItems1)
                        {                            
                                table.Rows[i]["noq"] = value;
                                i++;
                        }
                        foreach (var value in splitItems)
                        {
                            table.Rows[j]["sid"] = value;
                            j++;
                        }
                        Gridview1.DataSource = table;
                        Gridview1.DataBind();
                        Button1.Text = "Update";
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
 ========================================================================
Admin can View results of users 
ViewResults.aspx page code

<%@ Page Title="" Language="C#" MasterPageFile="~/AdminMaster.Master" AutoEventWireup="true" CodeBehind="ViewResults.aspx.cs" Inherits="OnlineExam.ViewResults" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


    <div class="row">
        <div class="col-lg-12">
            <h4> View results </h4>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="row">
        <table border="0" cellpadding="0" cellspacing="0" class="table table-striped table-bordered table-hover"
            align="center" style="width: 1189px; height: 795px;">
            <tr>
                <td>
               
            <asp:DropDownList ID="ddlshow" runat="server" AutoPostBack="True" class="form-control" Visible="false"
                                                TabIndex="1" Width="75px" OnSelectedIndexChanged="ddlshow_SelectedIndexChanged">
                                                <asp:ListItem Value="20">20</asp:ListItem>
                                                <asp:ListItem Value="50">50</asp:ListItem>
                                                <asp:ListItem Value="75">75</asp:ListItem>
                                                <asp:ListItem Value="100">100</asp:ListItem>
                                            </asp:DropDownList>

                                           
                  <div class="box-body">
                   

                  <table class="table table-bordered">
                   <asp:GridView ID="grdProperties" runat="server" AutoGenerateColumns="False" ShowFooter="true"
                                                CellPadding="4" CssClass="table table-hover table-bordered" GridLines="None"
                                                Width="101%" Style="margin-right: 20px"
                                             >                                              
                                                <RowStyle BackColor="#F5F5F5" />
                                                <AlternatingRowStyle BackColor="#FFFFFF" />
                                                <Columns>
                                                     

                                                     <asp:TemplateField HeaderText="Student ID" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblqst" runat="server" Text='<%# Gethtml(Eval("StudentID").ToString()) %>'></asp:Label>
                                                        </ItemTemplate>
                                                      
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Exam" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblctgry" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                                                        </ItemTemplate>
                                                       
                                                    </asp:TemplateField>
                                                    <asp:TemplateField HeaderText="Answered" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblfid" runat="server" Text='<%# Eval("Answered") %>'></asp:Label>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                     <asp:TemplateField HeaderText="Correct Answers" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblfid" runat="server" Text='<%# Eval("nocans") %>'></asp:Label>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                     <asp:TemplateField HeaderText="Un Answered" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblfid" runat="server" Text='<%# Eval("unans") %>'></asp:Label>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                     <asp:TemplateField HeaderText="Wrong" >
                                                        <ItemTemplate>
                                                            <asp:Label ID="lblfid" runat="server" Text='<%# Eval("wrong") %>'></asp:Label>
                                                        </ItemTemplate>
                                                    </asp:TemplateField>
                                                </Columns>
                                                <EmptyDataTemplate>
                                                    <b>No records found</b>
                                                </EmptyDataTemplate>
                                            </asp:GridView>
                  </table>
                </div><!-- /.box-body -->
                <div class="box-footer clearfix">
                <div style="float:right;">
                     <table cellpadding="0" border="0">
                        <tr><td>
                                <asp:Label ID="lblPageInfo" runat="server" style="font-weight: 700" Visible="false"></asp:Label>
                           </td><td>&nbsp;&nbsp;</td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnFirst" runat="server"
                                    CausesValidation="false" OnClick="lbtnFirst_Click" CssClass="paging" Visible="false">First</asp:LinkButton>
                                &nbsp;</td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnPrevious" CssClass="paging" runat="server"
                                    CausesValidation="false" OnClick="lbtnPrevious_Click"><<</asp:LinkButton>&nbsp;&nbsp;</td>
                            <td >
                                <asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand"
                                    OnItemDataBound="dlPaging_ItemDataBound">
                                    <ItemTemplate>
                                        <asp:LinkButton  ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
                                            CommandName="Paging" Text='<%# Eval("PageText") %>'></asp:LinkButton>&nbsp;
                                    </ItemTemplate>
                                    <SeparatorTemplate>&nbsp;|&nbsp;</SeparatorTemplate>
                                </asp:DataList>
                            </td>
                            <td align="left">
                                &nbsp;&nbsp;<asp:LinkButton CssClass="paging" ID="lbtnNext" runat="server" CausesValidation="false"
                                    OnClick="lbtnNext_Click">>></asp:LinkButton></td>
                            <td align="left">
                                &nbsp;
                                <asp:LinkButton ID="lbtnLast" runat="server" Visible="false" CausesValidation="false" OnClick="lbtnLast_Click" CssClass="paging">Last</asp:LinkButton></td>
                                <td style="padding-left:5px;">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="7" align="center" style="display:none;" valign="middle">
                                &nbsp;</td>
                        </tr>
                    </table></div>
                </div>
               
                </td>
              </tr></table>
                 
                  
                      
                    
                
                                   
                    </div>
</asp:Content>

 ========================================================================
ViewResults.aspx.cs page code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
using System.Globalization;


namespace OnlineExam
{
    public partial class ViewResults : System.Web.UI.Page
    {
        #region Declaration
        General clsGeneral = new General();
        comFunctions fssFunctions = new comFunctions();
        SqlDataAdapter adp;
        DataSet ds, dsHelp;
        string strLogUser;
        int Result;
        #endregion
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ToString());
        #region Private Properties
        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;
                if (objPage == null)
                {
                    _CurrentPage = 0;
                }
                else
                {
                    _CurrentPage = (int)objPage;
                }
                return _CurrentPage;
            }
            set { ViewState["_CurrentPage"] = value; }
        }
        private int fistIndex
        {
            get
            {

                int _FirstIndex = 0;
                if (ViewState["_FirstIndex"] == null)
                {
                    _FirstIndex = 0;
                }
                else
                {
                    _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
                }
                return _FirstIndex;
            }
            set { ViewState["_FirstIndex"] = value; }
        }
        private int lastIndex
        {
            get
            {

                int _LastIndex = 0;
                if (ViewState["_LastIndex"] == null)
                {
                    _LastIndex = 0;
                }
                else
                {
                    _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
                }
                return _LastIndex;
            }
            set { ViewState["_LastIndex"] = value; }
        }
        #endregion
        #region PagedDataSource
        PagedDataSource _PageDataSource = new PagedDataSource();
        #endregion
        string lang = "";


        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["uid"] == null)
            {
                ClientScriptManager csm = Page.ClientScript;
                csm.RegisterStartupScript(this.GetType(), "redirectlogin""<script  type='text/javascript' language='javascript'>parent.top.location.href='Login.aspx'; </script>");
                return;
            }
            try
            {
                string ConStr = ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString;
                cn = new SqlConnection(ConStr);
                if (cn.State == ConnectionState.Closed)
                {
                    cn.Open();
                }
                Page.MaintainScrollPositionOnPostBack = true;

                if (Page.IsPostBack == false)
                {
      
                    BindResults();
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
                throw ex;
            }
        }
      
        private bool WriteLog(string strError)
        {
            string AppPath = AppDomain.CurrentDomain.BaseDirectory;
            string strLog = @"LOG1\";
            string strFilePath = AppPath + strLog;

            if (!(Directory.Exists(strFilePath)))
            {
                Directory.CreateDirectory(strFilePath);
            }
            string fn = string.Format("{0}{1}.txt", strFilePath, DateTime.Now.ToString("ddMMyyyy"));
            FileStream fs = new FileStream(fn, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

            StreamWriter writer = new StreamWriter(fs);
            writer.Write("[ " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + " ]");
            writer.WriteLine(strError);
            writer.WriteLine("--------------------------------------------------------------------------");
            writer.Close();
            fs.Close();
            return true;
        }

      
        protected string Gethtml(string sttdesc)
        {

            return Server.HtmlDecode(sttdesc);
        }
        private DataSet GetUpcomingProperty()
        {
            try
            {
                if (cn.State == ConnectionState.Closed) { cn.Open(); };
                SqlDataAdapter myDataAdapter;
                myDataAdapter = new SqlDataAdapter("SELECT  E.ExamHistid,E.StudentID, E.noq, E.Answered, E.nocans, E.unans, E.wrong, S.Name FROM Exams E left join ExamMaster S on E.sid = S.Id", cn);
                myDataAdapter.SelectCommand.CommandType = CommandType.Text;
                dsHelp = new System.Data.DataSet();

                myDataAdapter.Fill(dsHelp); //helpus.CloseConnection();
                return dsHelp;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //helpus.CloseConnection();
            }
        }
        public void BindResults()
        {
            try
            {
                DataSet BindBatch = GetUpcomingProperty();
                if (BindBatch.Tables[0].Rows.Count > 0)
                {
                    DataTable dataTable = BindBatch.Tables[0];
                    _PageDataSource.DataSource = dataTable.DefaultView;
                    _PageDataSource.AllowPaging = true;
                    _PageDataSource.PageSize = Convert.ToInt32(ddlshow.SelectedValue);
                    _PageDataSource.CurrentPageIndex = CurrentPage;
                    ViewState["TotalPages"] = _PageDataSource.PageCount;

                    //this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
                    this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
                    this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
                    this.grdProperties.DataSource = _PageDataSource;
                    this.grdProperties.DataBind();
                    grdProperties.Columns[1].ItemStyle.Width = 180;
                    grdProperties.Columns[3].ItemStyle.Width = 90;
                    grdProperties.Columns[4].ItemStyle.Width = 90;
                    grdProperties.Columns[5].ItemStyle.Width = 90;
                    this.doPaging();
                }
                else
                {
                    grdProperties.DataSource = null;
                    grdProperties.DataBind();
                }
            }
            catch (Exception ex)
            {
            }
        }

   


        private void doPaging()
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("PageIndex");
                dt.Columns.Add("PageText");
                fistIndex = CurrentPage - 5;
                if (CurrentPage > 5)
                {
                    lastIndex = CurrentPage + 5;
                }
                else
                {
                    lastIndex = 10;
                }
                if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
                {
                    lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                    fistIndex = lastIndex - 10;
                }
                if (fistIndex < 0)
                {
                    fistIndex = 0;
                }
                for (int i = fistIndex; i < lastIndex; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = i;
                    dr[1] = i + 1;
                    dt.Rows.Add(dr);
                }
                this.dlPaging.DataSource = dt;
                this.dlPaging.DataBind();
            }
            catch (Exception ex)
            {
                WriteLog("ViewProperty.aspx--doPaging()--" + Session["UserLog"].ToString() + "--" + ex.Message);
                throw ex;
            }
        }

        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            this.BindResults();
        }
        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindResults();
        }
        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            this.BindResults();
        }
        protected void lbtnLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            this.BindResults();
        }
        protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("Paging"))
            {
                CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
                this.BindResults();
            }
        }
        protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType != ListItemType.Separator)
                {
                    LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
                    if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
                    {
                        lnkbtnPage.Enabled = false;
                        lnkbtnPage.Style.Add("fone-size""14px");
                        lnkbtnPage.Font.Bold = true;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("ViewProperty.aspx--dlPaging_ItemDataBound()--" + Session["UserLog"].ToString() + "--" + ex.Message);
                throw ex;
            }

        }
        protected void ddlshow_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindResults();
        }
        protected void ddlSubCat_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
      
    }
}
==========================================================================================







<%@ Page Title="" Language="C#" MasterPageFile="~/MainPage.Master" AutoEventWireup="true" CodeBehind="Exam.aspx.cs" Inherits="OnlineExam.Exam" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"><div align="center">
<link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"
        type="text/css" /> 
        <link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<asp:ScriptManager ID="ScriptManager1" runat="server">
                            </asp:ScriptManager>

                            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                                <ContentTemplate><asp:timer ID="Timer1" Interval="1000" OnTick="timer1_tick" runat="server"></asp:timer> </ContentTemplate></asp:UpdatePanel>
                            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                                <ContentTemplate>
<table  align="center" cellpadding="0" cellspacing="0" width="990">
        <tr>
            <td>
                <table  align="center" cellpadding="0" cellspacing="0" width="990" bgcolor="#dddddd" >
                    <tr>


                        <td class="style10">
                            &nbsp;</td>
                        <td style="height: 22px">
                            &nbsp;</td>
                    </tr>
                    <tr>
                        <td class="style10">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Student ID :
                            <asp:Label ID="lblSid" runat="server" Font-Bold="True" Font-Names="Verdana"
                                ForeColor="Red" Width="154px"></asp:Label>
                        </td>
                        <td style="height: 22px">
                            Number of Questions :<asp:Label ID="lblrange" runat="server" Font-Bold="True"
                                Font-Names="Verdana" ForeColor="Red"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td class="style10">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Progrmme :
                            <asp:Label ID="lblprogrm" runat="server" Font-Bold="True" Font-Names="Verdana"
                                ForeColor="Red"></asp:Label>
                        </td>
                        <td style="height: 22px">
                            Start Time ::<asp:Label ID="lbldate" runat="server" Font-Bold="True"
                                Font-Names="Verdana" ForeColor="Red"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td class="style10">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;
                            <asp:Label ID="lblsub" runat="server" Font-Bold="True" Font-Names="Verdana"
                                ForeColor="Red"></asp:Label>
                        </td>
                        <td style="height: 22px">
                            Remaining Time ::<asp:Label ID="lblTimer" Font-Bold="True"
                                Font-Names="Verdana" ForeColor="Red" runat="server"></asp:Label>
                        </td>
                    </tr>
                 
                </table>
              
                <br />
            </td>
        </tr>
        <tr>
            <td align="center">
            <span style="font-weight: bold; color: #993300; font-size: small;">Question: &nbsp; <asp:Label ID="lblQ"  runat="server" Text=""></asp:Label></span>
                  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        ShowFooter="True" Width="956px" >
        <Columns>


                 

            <asp:TemplateField>
               
                <ItemTemplate>
                <table><tr> <td> &nbsp; </td> <td><asp:Label ID="lblQstn" Visible="false" runat="server" Text='<%#  Eval("qid")%>'></asp:Label>
                  <asp:Label ID="lblans" Visible="false" runat="server" Text='<%#  Eval("cans")%>'></asp:Label>
                 <asp:Label ID="Label2" runat="server" Text='<%#  Eval("question")%>'></asp:Label></td> </tr></table>
                   
                  
                   &nbsp;   1.<asp:RadioButton ID="ra1" runat="server" GroupName="GA1"
                        Text='<%#Eval("option1") %>'
                        oncheckedchanged="ra1_CheckedChanged" />
                    <br />
                  &nbsp;    2.<asp:RadioButton ID="ra2" 
                        oncheckedchanged="ra2_CheckedChanged"  runat="server" GroupName="GA1" Text='<%#Eval("option2") %>'  />
                    <br />
                 &nbsp;     3.<asp:RadioButton ID="ra3" 
                        oncheckedchanged="ra3_CheckedChanged" runat="server" GroupName="GA1" Text='<%#Eval("option3") %>' />
                    <br />
                  &nbsp;    4.<asp:RadioButton ID="ra4"
                        oncheckedchanged="ra4_CheckedChanged" runat="server" GroupName="GA1" Text='<%#Eval("option4") %>' />
                    <br /> <br />
                </ItemTemplate>
                <FooterTemplate>
                 
                                   &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;
                                   
                   
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
       
    </asp:GridView>
            </td>
        </tr>
        <tr>
            <td>  <table class="table table-striped table_vam no-th" data-rowlink="a">
                                                <tr><td><div style="float:left;">
            <table cellpadding="0" border="0">
 <tbody>

  <tr>
   <td><span class="not_visited" title="Not Visited">&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Button2" runat="server"    Text="" class="btn btn-default"  Width="20px" /></span>
    </td>  <td> &nbsp;not visited&nbsp; &nbsp;</td>

    <td><span class="not_answered" title="Not Answered">
      <asp:Button ID="Button3" runat="server" Text="" class="btn btn-info"  Width="20px" /></span></td>
       <td>  &nbsp;not answered&nbsp; &nbsp;</td>

       <td><span class="answered" title="Answered">
       <asp:Button ID="Button4" runat="server"   Text="" class="btn btn-success"  Width="20px" /></span></td>
        <td>  &nbsp;answered &nbsp;&nbsp;</td>



 <td><span class="review" title="Marked for Review">
        <asp:Button ID="Button5" runat="server"    Text="" class="btn btn-warning"  Width="20px" /></span></td>
         <td>  &nbsp; NOT answered & marked review.&nbsp; &nbsp;</td>
  
    
    
          <td><span class="review_answered" title="Answered &amp; Marked for Review">
          <asp:Button ID="Button6" runat="server"    Text="" class="btn btn-danger"  Width="20px" /></span></td>
           <td>  &nbsp;  answered & marked review.&nbsp; &nbsp;</td>
     
             </tbody>  </table> </div></td></tr>
                                                </table>
          
                   
            <table class="table table-striped table_vam no-th" data-rowlink="a">
                                                <tr><td><div style="float:left;">
                        <table cellpadding="0" border="0">
                         <tr>
                            <td colspan="7" >
                                &nbsp; &nbsp; &nbsp;<asp:Button  ID="lbtnNext" runat="server" CausesValidation="false"
                              class="btn btn-primary btn-primary-blue"    Text="Save & Next"  OnClick="lbtnNext_Click"  />    &nbsp; &nbsp; &nbsp;<asp:Button  ID="btnReviewLater" runat="server" CausesValidation="false"
                               class="btn btn-primary btn-primary-blue"   Text="Review Later"  OnClick="btnReviewLater_Click"  /></td>
                        </tr>
                        <tr>
                        <td>
                                <asp:Label ID="lblPageInfo" runat="server" Visible="false" style="font-weight: 700"></asp:Label>
                           </td>
                           <td>&nbsp;&nbsp;</td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnFirst" runat="server"
                                 Visible="false"   CausesValidation="false" OnClick="lbtnFirst_Click" CssClass="paging">First</asp:LinkButton>
                                &nbsp;</td>
                            <td align="right">
                                <asp:LinkButton ID="lbtnPrevious" CssClass="paging" runat="server"
                                  Visible="false"  CausesValidation="false" OnClick="lbtnPrevious_Click">Previous</asp:LinkButton>&nbsp;&nbsp;</td>
                            <td >
                                <asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand"
                                  OnItemDataBound="dlPaging_ItemDataBound">
                                    <ItemTemplate>
                                   
                                        <asp:Button CommandArgument='<%# Eval("PageIndex") %>'
                                          Height="30px" Width="30px"  CommandName="Paging" Text='<%# Eval("PageText") %>' ID="lnkbtnPaging" runat="server"  Font-Bold="True" ForeColor="Black" />    &nbsp;
                                    </ItemTemplate>
                                    <SeparatorTemplate>&nbsp;|&nbsp;</SeparatorTemplate>
                                </asp:DataList>

                            </td>
                            <td align="left">

                                &nbsp;&nbsp;
                                <asp:Button ID="Button1" runat="server" class="btn btn-primary btn-primary-blue" onclick="Button1_Click" Text="Stop & View result" />
                                </td>
                            <td align="left">
                                &nbsp;
                                <asp:LinkButton ID="lbtnLast" Visible="false" runat="server" CausesValidation="false" OnClick="lbtnLast_Click" CssClass="paging">Last</asp:LinkButton></td>
                                <td style="padding-left:5px;">&nbsp;</td>
                        </tr>
                      
                    </table></div></td></tr>
                                                </table>
                <br />
                <br />
            </td>
        </tr>
    </table>
    </ContentTemplate></asp:UpdatePanel>
  <%--  <Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>--%>
    </div>
</asp:Content>

 =======================================================================
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Configuration;

namespace OnlineExam
{
    public partial class Exam : System.Web.UI.Page
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        SqlDataAdapter adp;
        SqlCommand cmd , cmd1;
        int i = 0;
        int opt;
        int increment = 0;
        string s, h, m;
    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];
            int _CurrentPage = 0;
            if (objPage == null)
            {
                _CurrentPage = 0;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    }
    private int fistIndex
    {
        get
        {

            int _FirstIndex = 0;
            if (ViewState["_FirstIndex"] == null)
            {
                _FirstIndex = 0;
            }
            else
            {
                _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
            }
            return _FirstIndex;
        }
        set { ViewState["_FirstIndex"] = value; }
    }
    private int lastIndex
    {
        get
        {

            int _LastIndex = 0;
            if (ViewState["_LastIndex"] == null)
            {
                _LastIndex = 0;
            }
            else
            {
                _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
            }
            return _LastIndex;
        }
        set { ViewState["_LastIndex"] = value; }
    }

        PagedDataSource _PageDataSource = new PagedDataSource();
        Dal info = new Dal();
        public int SIZE = 25;
        public int mid;
        public int sid;
        public String sname;
        public int ncans;
        public List<Question> questions;
        public DateTime StartTime;
        public int curpos = 0;
        string[] answr = new string[100];




        public void BindExam()
        {
            try
            {
                DataSet BindBatch = (DataSet)Session["questionpaper"];
                if (BindBatch.Tables[0].Rows.Count > 0)
                {
                    DataTable dataTable = BindBatch.Tables[0];
                    _PageDataSource.DataSource = dataTable.DefaultView;
                    _PageDataSource.AllowPaging = true;
                    _PageDataSource.PageSize = 1;
                    _PageDataSource.CurrentPageIndex = CurrentPage;
                   
                    ViewState["TotalPages"] = _PageDataSource.PageCount;

                    this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
                  
                    this.GridView1.DataSource = _PageDataSource;
                    this.GridView1.DataBind();
                  
                    this.doPaging();
                    //this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
                    //this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
                }
                else
                {
                    GridView1.DataSource = null;
                    GridView1.DataBind();
                }
            }
            catch (Exception ex)
            {
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddProperty.aspx");
        }
      


        private void doPaging()
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("PageIndex");
                dt.Columns.Add("PageText");
                fistIndex = CurrentPage - 5;
                if (CurrentPage > 5)
                {
                    lastIndex = CurrentPage + 5;
                }
                else
                {
                    lastIndex = 10;
                }
                if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
                {
                    lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                    fistIndex = lastIndex - 10;
                }
                if (fistIndex < 0)
                {
                    fistIndex = 0;
                }
                for (int i = fistIndex; i < lastIndex; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = i;
                    dr[1] = i + 1;
                    dt.Rows.Add(dr);
                }
                this.dlPaging.DataSource = dt;
                this.dlPaging.DataBind();
            }
            catch (Exception ex)
            {
              
                throw ex;
            }
        }

        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            this.BindExam();
        }
        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindExam();
        }
        protected void lbtnNext_Click(object sender, EventArgs e)
        {

            DataSet BindBatch = (DataSet)Session["questionpaper"];
            int j = BindBatch.Tables[0].Rows.Count;

            GridViewRow row = GridView1.Rows[0];
            Label hdnField = (Label)row.FindControl("lblQstn");
            Label hdnans = (Label)row.FindControl("lblans");
            RadioButton r1 = (RadioButton)row.FindControl("ra1");
            RadioButton r2 = (RadioButton)row.FindControl("ra2");
            RadioButton r3 = (RadioButton)row.FindControl("ra3");
            RadioButton r4 = (RadioButton)row.FindControl("ra4");
            if (r1.Checked == true || r2.Checked == true || r3.Checked == true || r4.Checked == true)
            {
                if (r1 != null && r1.Checked)
                {

                    opt = 1;

                }
                else if (r2 != null && r2.Checked)
                {
                    opt = 2;
                }
                else if (r3 != null && r3.Checked)
                {
                    opt = 3;
                }
                else if (r4 != null && r4.Checked)
                {
                    opt = 4;
                }


                con.Open();
                cmd = new SqlCommand("update ExamHistory set Type = 3, Choise = '" + opt + "'  where Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "'   and   Qid = '" + Convert.ToInt32(hdnField.Text) + "'  and Ans = '" + hdnans.Text + "' ", con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                con.Close();
            }
            if (j != CurrentPage+1)
            {
                CurrentPage += 1;
            }
       
         
         
            this.BindExam();
        }
        protected void btnReviewLater_Click(object sender, EventArgs e)
        {
            DataSet BindBatch = (DataSet)Session["questionpaper"];
            int j = BindBatch.Tables[0].Rows.Count;

            GridViewRow row = GridView1.Rows[0];
            Label hdnField = (Label)row.FindControl("lblQstn");
            RadioButton r1 = (RadioButton)row.FindControl("ra1");
            RadioButton r2 = (RadioButton)row.FindControl("ra2");
            RadioButton r3 = (RadioButton)row.FindControl("ra3");
            RadioButton r4 = (RadioButton)row.FindControl("ra4");
            if (r1.Checked == true || r2.Checked == true || r3.Checked == true || r4.Checked == true)
            {
                if (r1 != null && r1.Checked)
                {

                    opt = 1;

                }
                else if (r2 != null && r2.Checked)
                {
                    opt = 2;
                }
                else if (r3 != null && r3.Checked)
                {
                    opt = 3;
                }
                else if (r4 != null && r4.Checked)
                {
                    opt = 4;
                }
                con.Open();
                cmd = new SqlCommand("update ExamHistory set Type = 4, Choise = '" + opt + "' where Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "'   and   Qid = '" + Convert.ToInt32(hdnField.Text) + "'  ", con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                con.Close();
            }
            if (r1.Checked == false && r2.Checked == false && r3.Checked == false && r4.Checked == false)
            {
                con.Open();
                cmd = new SqlCommand("update ExamHistory set Type = 5 where Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "'   and   Qid = '" + Convert.ToInt32(hdnField.Text) + "'  ", con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                con.Close();
            }


            if (j != CurrentPage + 1)
            {
                CurrentPage += 1;
            }
            this.BindExam();
        }
        protected void lbtnLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            this.BindExam();
        }

        protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("Paging"))
            {
                CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
                this.BindExam();
            }
        }
        protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            try
            {
                DataSet BindBatch = (DataSet)Session["questionpaper"];
                if (e.Item.ItemType != ListItemType.Separator)
           //     if (e.Item.ItemType == ListItemType.Item ||
           //e.Item.ItemType == ListItemType.AlternatingItem)
                {
                   
                    Button lnkbtnPage = (Button)e.Item.FindControl("lnkbtnPaging");
                   // if (lnkbtnPage.Text == CurrentPage.ToString())
                    if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
                    {
                       
                        lblQ.Text = (CurrentPage + 1).ToString();
                        GridViewRow row = GridView1.Rows[0];
                        Label hdnField = (Label)row.FindControl("lblQstn");
                        RadioButton r1 = (RadioButton)row.FindControl("ra1");
                        RadioButton r2 = (RadioButton)row.FindControl("ra2");
                        RadioButton r3 = (RadioButton)row.FindControl("ra3");
                        RadioButton r4 = (RadioButton)row.FindControl("ra4");

                        if (r1.Checked == false && r2.Checked == false && r3.Checked == false && r4.Checked == false)
                        {
                              adp = new SqlDataAdapter("select Type from ExamHistory where  Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "' and Qid = '" + BindBatch.Tables[0].Rows[i]["qid"] + "'   ", con);

                    ds = new DataSet();
                    adp.Fill(ds);

                    if (ds.Tables[0].Rows.Count > 0)
                    {



                        int j = Convert.ToInt32(ds.Tables[0].Rows[0]["Type"]);

                        if (j == 1)
                        {
                            con.Open();
                            cmd = new SqlCommand("update ExamHistory set Type = 2 where Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "'   and   Qid = '" + Convert.ToInt32(hdnField.Text) + "'  ", con);
                            cmd.CommandType = CommandType.Text;
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                      

                    }
                        }

                    adp = new SqlDataAdapter("select Type, Choise from ExamHistory where  Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "' and Qid = '" + BindBatch.Tables[0].Rows[i]["qid"] + "'   ", con);
                    ds = new DataSet();
                    adp.Fill(ds);

                    if (ds.Tables[0].Rows.Count > 0)
                    {                    
                        int j = Convert.ToInt32(ds.Tables[0].Rows[0]["Choise"]);
                        if (j == 1)
                            r1.Checked = true;
                        if (j == 2)
                            r2.Checked = true;
                        if (j == 3)
                            r3.Checked = true;
                        if (j == 4)
                            r4.Checked = true;
                        if (j == 0)
                        {
                            r1.Checked = false;
                            r2.Checked = false;
                            r3.Checked = false;
                            r4.Checked = false;
                        }
                    }

                    }
                   
                    adp = new SqlDataAdapter("select Type from ExamHistory where  Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "' and Qid = '" + BindBatch.Tables[0].Rows[i]["qid"] + "'   ", con);

                    ds = new DataSet();
                    adp.Fill(ds);
                 
                    if (ds.Tables[0].Rows.Count > 0)
                    {


                    
                            int j = Convert.ToInt32(ds.Tables[0].Rows[0]["Type"]);
                            if (j == 0)
                            {

                                lnkbtnPage.Attributes.Add("class", "btn btn-default");
                              
                            }
                            if (j == 1)
                            {

                                lnkbtnPage.Attributes.Add("class", "btn btn-default");
                            }
                            if (j == 2)
                            {
                                lnkbtnPage.Attributes.Add("class", "btn btn-info");
                               
                            }
                            if (j == 3)
                            {
                                lnkbtnPage.Attributes.Add("class", "btn btn-success");
                              
                            }
                            if (j == 4)
                            {

                                lnkbtnPage.Attributes.Add("class", "btn btn-warning");
                            }
                            if (j == 5)
                            {

                                lnkbtnPage.Attributes.Add("class", "btn btn-danger");
                            }

                       // }

                    }
                    i++;
                 
                }
            }
            catch (Exception ex)
            {
              
                throw ex;
            }

        }





    

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] == null)
            {
                Response.Redirect("index.aspx");
            }
            if (!Page.IsPostBack)
            {
                BindExam();
                lblSid.Text = Session["UserName"].ToString();
                //lblsub.Text = Request.QueryString["subject"];
                adp = new SqlDataAdapter("select Name,time  from ExamMaster  where Id ='" + Convert.ToInt32(Request.QueryString["p"]) + "'", con);
            ds = new DataSet();
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                lblprogrm.Text = (ds.Tables[0].Rows[0]["Name"]).ToString();
                Session["Etime"] = DateTime.Now.AddMinutes(Convert.ToInt32(ds.Tables[0].Rows[0]["time"]));
            }
                //lbltopic.Text = Request.QueryString["subtopic"];
                //lbllvl.Text = Request.QueryString["level"];
                //lblrange.Text = Request.QueryString["range"];
            }

        }
        protected void timer1_tick(object sender, EventArgs e)
        {
            TimeSpan time1 = new TimeSpan();
            time1 = (DateTime)Session["Etime"] - DateTime.Now;
            if (time1.TotalMinutes < 0)
            {
                finishtest();
            }
            else
            {
                if (time1.Hours.ToString().Length == 1)
                {
                    h = "0" + time1.Hours.ToString();
                }
                else
                {
                    h = time1.Hours.ToString();
                }
                if (time1.Minutes.ToString().Length == 1)
                {
                    m = "0" + time1.Minutes.ToString();
                }
                else
                {
                    m = time1.Minutes.ToString();
                }
                if (time1.Seconds.ToString().Length == 1)
                {
                    s = "0" + time1.Seconds.ToString();
                }
                else
                {
                    s = "0" + time1.Seconds.ToString();
                }
                lblTimer.Text = "hh:mm:ss" + " " + h + ":" + m + ":" + s;
            }

        }   
        protected void Button1_Click(object sender, EventArgs e)
    {
        finishtest();
      
        }

        private void finishtest()
        {

            DataSet ds2 = new DataSet();
            ds2 = (DataSet)Session["questionpaper"];
            //Sid is Exam name ID
            adp = new SqlDataAdapter("select * from ExamHistory where  Sid ='" + Convert.ToInt32(Request.QueryString["p"]) + "' and StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Session["ExamId"]) + "'   ", con);
            ds = new DataSet();
            adp.Fill(ds);
            int u = 0, v = 0;
            if (ds.Tables[0].Rows.Count > 0)
            {
                List<int> cans = new List<int>();
                List<int> myansws = new List<int>();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    cans.Add(Convert.ToInt32(row["Ans"]));
                }
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    myansws.Add(Convert.ToInt32(row["Choise"]));
                }
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (Convert.ToInt32(row["Choise"]) == 0)
                        u++;
                    else
                        v++;
                }
                int scr;
                scr = cans.Intersect(myansws).Count();
                int m = cans.Count - (scr + u);
                string prg = lblprogrm.Text;
                string sub = lblsub.Text;
                string rng = lblrange.Text;
                int n = info.insertexamdetails(Session["Username"].ToString(), Convert.ToInt32(Request.QueryString["p"]), Convert.ToInt32(Session["ExamId"]), cans.Count, v, scr, m, u);
                if (n > 0)
                {
                    Session["Stoptime"] = DateTime.Now;
                    Response.Redirect("Result.aspx?p=" + n);
                }
                if (n == -1)
                {
                    //lblres.Text = "Exists !!!";
                }

            }
        }
        protected void ra1_CheckedChanged(object sender, EventArgs e)
        {
          
        }
        protected void ra2_CheckedChanged(object sender, EventArgs e)
        {

        }
        protected void ra3_CheckedChanged(object sender, EventArgs e)
        {

        }
        protected void ra4_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}






20 comments:

  1. where's the MainPage.Master plssss comment?

    ReplyDelete
  2. please send me a full source code plss for my thesis help me :(

    ReplyDelete
  3. Hi am learner of asp.net plz send your code for learning purpouse

    ReplyDelete
  4. can i get this full project please
    kaushiknandwana@gmail.com

    ReplyDelete
  5. ccan u upload rest pleease

    ReplyDelete
  6. Hello sir kia ap ye sara project mujy send kar sakty hai sir

    ReplyDelete
  7. Sanjeevan Kumar4 July 2017 at 12:38

    Sir, can you give me the source code of this project...plz

    ReplyDelete
  8. Please Paste the following classes source code other wise your article is not used any body
    General
    SqlHelper
    comFunctions
    Dal

    ReplyDelete
  9. please send code to ymkamt@gmail.com...

    ReplyDelete
  10. Hello Sir , This is very good good project for help with good admin panel, But m getting errors when trying to run full project ,like in User entry its showing OnlineExam,BL not exists in SqlHelper.ExecuteNonQuery(ConnectionString.GetConnectionString(), CommandType.StoredProcedure, "spRegistration", p);.
    error in Connectionstring
    can you provide complete project on gnss1234@gmail.com

    Highly Appreciated

    ReplyDelete
  11. please can you send me full project to nuribaba27@gmail.com.

    ReplyDelete
  12. can you send me full project to chandrasekhar4a9@gmail.com.

    ReplyDelete
  13. can you please send me complete project to arslan.ahmad14@gmail.com


    Thanks

    ReplyDelete
  14. can you please send me complete project to tarunmaity199@gmail.com

    ReplyDelete
  15. can you please send me complete project to cheleyader26@gmail.com

    ReplyDelete
  16. can you please send me full project to cheleyader26@gmail.com

    ReplyDelete