29 Jun 2017

How to form client side authentication through angular 1

How to form client side authentication through angular 1 


Guest post :

Can anybody tell me how to form client side authentication through angular 1 so that we can call an API after.

Solution :

oAuth or Json Web Token. I used both and the second one seems to be more friendly.

In JWT(Json web token) you can use angular-jwt directive.


26 Jun 2017

Improve SQL server query performance on table with millions of records.

Improve SQL server query performance on table with millions of records.


Guest post : 

Hi I have a table with 1+ Million records. The Query Is very slow when I use a where.
For Paging I am using ROW_NUMBER() OVER (ORDER BY CreatedOn DESC) AS ROW_NUM
Can some one help me with best practices while creating table also best way to create ROW_NUM for Paging.

Solution :

Indexing the table is a good option.

If your table is not dyamic load table using Ajax in jquery datatable. It can handle rows efficiently.

Use a parameterized store procedure in parameter take the number of record and last starting that will optimize your code.

Users please post your solution too.

24 Jun 2017

whats the difference between asynchronous and multithreading

whats the difference between asynchronous and multithreading


You just have to look at the word "asynchronous". Synchronous means that all of the things are done at once. So asynchronous, as its opposite, means that everything is not done at once, but may occur at any time, rather than in a specific order.

Multithreading is asynchronous, because each thread is working independently, and may call for a certain response from the main thread at any time.

Threading is about 'workers', asynchrony is about tasks. 
A greate example I have read somewhere else: 

Synchronous: you 'cook' the eggs then you 'cook' the toast

Asynchronous single threaded: you start the eggs cooking and set a timer. You start the toast cooking, and set a timer. While they are both cooking, you clean the kitchen. When the timers go off you take the eggs off the heat and the toast out of the toaster and serve them.

Asynchronous multi threaded: you hire two more cooks, one to cook eggs and one to cook toast. Now you have the problem of coordinating the cooks so that they do not conflict with each other in the kitchen when sharing resources. And you have to pay them.

"synchronous" means that you block on the call until it finishes executing. Asynchronous means you do not block. You can't say that synchronous means "at once" because that implies that everything is happening simultaneously. If I fire off 5 web requests synchronously, then they each happen one after another, and I don't continue on with other code until all 5 return--again, one after another. If I make those same 5 requests asynchronously, then they most certainly can happen at the same time. Now, those may not finish at the same time, but they (more than likely) are being processed at the same time. I can even continue on with other code, and expect those 5 results at a later time should I so desire. That's the beauty of async/await.

In the async/await world, we are typically using async to avoid blocking on I/O logic. When the hardware is busy doing stuff outside of the CPUs purview, then the CPU accomplishes nothing meaningful while it sits there waiting for I/O to complete. We use async code to allow the CPU to continue on with meaningful work while the hardware finishes its tasks. When the hardware is done, it signals the CPU using an I/O completion port (or crudely, the hardware signals the CPU/raises an event with the CPU).

Also, you cannot say that multi-threading is asynchronous. It can be. I can kick off a thread to make one of those web requests I mentioned above. But creating a thread incurs a bit of overhead. You can certainly have synchronous threads. You can force one thread to wait until some other thread reaches some arbitrary point. Now you have to do this using shared resources, which must be protected from corruption. This protection is part of what makes multi-threading code so difficult.

Changing DIV value using jquery Asp.net MVC

Changing DIV value using jquery Asp.net MVC

Guest post 
I have one div division

<div id="myname" name="myname">myvalue</div>

i am changing value of "myvalue" with jquery 
how can i pass myvalue to my controller.

Solution
create a controller get the value by $("#myname").text(); 
and pass it into the controller like this 

for example this is my controller 

[HttpPost]
    public void UpdateTask(TaskModel tmdl)
    {
        sDBSEntities dbOBj = new sDBSEntities();
        Task tObj = dbOBj.Tasks.Single(x => x.ID == tmdl.ID);
        tObj.Name = tmdl.Name;
        tObj.Description = tmdl.Description;
        tObj.DateUpdated = DateTime.Now;
        dbOBj.SaveChanges();
    }


my ajax call would be

var tmdl = {
ID: $("#hdnId").val(),
Name: $("#txtName").val(),
Description: $("#txtDesc").val()
};
$.ajax({
type: 'POST',
url: '/Task/UpdateTask',
data: tmdl,
cache: false,
success: function (result) {
clearAll();
alert("Updated Successfully");
location.reload();
},
error: function () {
alert('Err');
}
});
}


you can post your solution below.

21 Jun 2017

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

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





StartExam.aspx page code


<%@ Page Title="" Language="C#" MasterPageFile="~/MainPage.Master" AutoEventWireup="true" CodeBehind="StartExam.aspx.cs" Inherits="OnlineExam.StartExam" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
      function validate() {
          if (document.getElementById("<%=disclaimer.ClientID%>").Checked == false) {
              alert("Please check Terms & Conditions");
            
              return false;
          }
      }
    
      }
    </script>
 <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"/>



<div id="divFirst" runat="server">
<table align="center" cellspacing="1" >
        <tr>
               
                <td class="style15">
                                        &nbsp;</td>
            </tr>
            <tr>
           
               
                <td>
                                        <table align="center" style="width: 650px; height: 450px;" cellpadding="10px" cellspacing="3px">
                                            <tr>
                                               <td align="right" class="style13" style="font-weight: bold">
                                                    Student Id :
                                                </td>
                                                <td align="left" class="style11">
                                                    <asp:TextBox ID="txt_stdId" runat="server" CssClass="textbox" Width="135px"
                                                        ReadOnly="True"></asp:TextBox><%--onkeydown="&#13;&#10;   if ( !isAlpha ( event ) ) {&#13;&#10;      alert ( 'Oops! Alphabets only please.' );&#13;&#10;      return false;&#13;&#10;   }"--%>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td align="right" class="style13" style="font-weight: bold">
                                                    Select Subjuct :
                                                </td>
                                                <td align="left" class="style11">
                                                    <asp:DropDownList ID="DdlProgrm" runat="server" Height="23px" Width="133px"
                                                      
                                                       >
                                                    
                                                    </asp:DropDownList>
                                                    <asp:RequiredFieldValidator ID="rfvlname0" runat="server" ControlToValidate="DdlProgrm"
                                                       ToolTip="program Required!" ValidationGroup="valid"><img src="images/question.gif" width="15px" height="15px"/></asp:RequiredFieldValidator>
                                                </td>
                                            </tr>
                                        
                                           
                                            <tr>
                                                <td align="right" class="style13" style="font-weight: bold">
                                                    &nbsp;</td>
                                                <td align="left" class="style11">
                                                    <asp:ImageButton ID="ImgBtnStartExm" runat="server"
                                                        ImageUrl="~/IMAGES/button copy.PNG" onclick="ImgBtnStartExm_Click" />
                                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                    <br />
                                                </td>
                                            </tr>
                                           
                                            <tr>
                                                <td align="right" class="style14">
                                                </td>
                                                <td align="left" class="RadioButton"  valign="middle" class="style12">
                                                 
                                                    &nbsp;&nbsp;
                                                 &nbsp;</td>
                                               
                                            </tr>
                                            <tr>
                                              
                                               
                                                <td align="left" class="style14">
                                                    &nbsp;&nbsp; &nbsp;</td>
                                            </tr>
                                        </table>
                                    </td>
            </tr>
        </table>
        </div>

        <div id="divSecond" runat="server">
                           <div id="firstPage" style="overflow: hidden; border-bottom: 1px solid rgb(204, 204, 204); padding-left: 20px; >
                                  <span style="float:right;display:none;padding:2px;"><br>
                           <div class="sysInstText1"
                        style="height: 99%; width: 100%; overflow: auto; text-align: left;"><div> <br>
<br>
<center style="font-size: large; color: #663300"><b>Please read the instructions carefully
    </b></center> </div>
<p style="text-align: left"><strong><u>General Instructions:</u></strong></p>
<ol style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px">  <li>Total duration of examination is <span class="completeDuration"></span> </li>  <li>The clock will be set at the server. The countdown timer in the top right corner of screen will display the remaining time available for you to complete the examination. When the timer reaches zero, the examination will end by itself. <table class="instruction_area" style="FONT-SIZE: 100%">  <tbody>  <tr>  <td><span class="not_visited" title="Not Visited">
    <asp:Button ID="Button2" runat="server"    Text="" class="btn btn-default"  Width="40px" /></span></td>  <td> &nbsp; &nbsp;You have not visited the question yet.</td>
     </tr>  <tr>  <td><span class="not_answered" title="Not Answered">
      <asp:Button ID="Button3" runat="server" Text="" class="btn btn-info"  Width="40px" /></span></td>
       <td>  &nbsp; &nbsp;You have not answered the question.</td>  </tr>  <tr>  <td><span class="answered" title="Answered">
       <asp:Button ID="Button4" runat="server"   Text="" class="btn btn-success"  Width="40px" /></span></td>
        <td>  &nbsp; &nbsp;You have answered the question.</td>  </tr>  <tr>  <td><span class="review" title="Marked for Review">
        <asp:Button ID="Button5" runat="server"    Text="" class="btn btn-warning"  Width="40px" /></span></td>
         <td>  &nbsp; &nbsp;You have NOT answered the question, but marked for review.</td>  </tr>  <tr>
          <td><span class="review_answered" title="Answered &amp; Marked for Review">
          <asp:Button ID="Button6" runat="server"    Text="" class="btn btn-danger"  Width="40px" /></span></td>
           <td>  &nbsp; &nbsp;You have answered the question, but marked for review.</td>  </tr>  </tbody>  </table>  </li>
            <li style="LIST-STYLE-TYPE: none">The Marked for Review status for a question simply indicates that you would like to look at that question again.</li>
                    </ol>
                    <div style="text-align: left">
                        <br> <strong><u>Navigating to a Question:</u></strong><br>
                    </div>
<ol start="4" style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px">  <li>
    To answer a question, do the following<ol style="TEXT-ALIGN: left; PADDING-LEFT: 4%; PADDING-TOP: 3px" type="a">  <li>Click on the question number in the Question Palette at the right of your screen to go to that numbered question directly. </li>  <li>Click on <b>Save &amp; Next</b> to save your answer for the current question and then go to the next question.</li>  <li>Click on <b>Mark for Review &amp; Next</b> to save your answer for the current question, mark it for review, and then go to the next question.</li>
    </ol>
    </li>
                    </ol>
                    <p style="text-align: left"> <b><u>Answering a Question : </u></b></p>
<ol start="5" style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px">  <li>Procedure for answering a multiple choice type question:<ol style="TEXT-ALIGN: left; PADDING-LEFT: 4%; PADDING-TOP: 3px" type="a">  <li>To select your answer, click on the button of one of the options</li>  <li>To mark the question for review, click on the<b> Mark for Review &amp; Next</b> button.</li>
    </ol>
    <br>
    </li>
                    </ol>
<p style="text-align: left"> <b><u>Navigating through sections:</u></b></p>
<ol start="6" style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px</ol>
       
        <p>
     
                                        
                                                  
                                                <span ></span><span ><span style="" class="cusInstText1"><input runat="server" type="checkbox" id="disclaimer" onclick="linkDisp();" style="margin-top:2px;margin-right:10px">I have read and understood the instructions. </span></span></p>
                <p>
     
                                        
                                                &nbsp;</p>
        <p>
            <asp:Button  class="btn btn-primary btn-primary-blue" ID="Button1"
             OnClientClick="return validate();"   runat="server" Text="I am ready to begin" onclick="Button1_Click" /></p>
                <p>
                    &nbsp;</p>
        </div></div></div>
</asp:Content>

 ===============================================================

StartExam.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.Data.SqlClient;
using System.IO;


namespace OnlineExam
{
    public partial class StartExam : System.Web.UI.Page
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        SqlDataAdapter adp ;
        SqlCommand cmd ;
        SqlCommand cmd1;
        Dal info = new Dal();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["Username"] == null)
                {
                    Response.Redirect("index.aspx");

                }
                bindSubjucts();
                txt_stdId.Text = Session["Username"].ToString();
                divFirst.Visible = true;
                divSecond.Visible = false;
            }
        }
        private void WriteLog(string strError)
        {
            try
            {
                string AppPath = AppDomain.CurrentDomain.BaseDirectory;
                string strLog = @"LOGS\";
                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
            }


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

        protected void ImgBtnStartExm_Click(object sender, ImageClickEventArgs e)
        {
            if (DdlProgrm.SelectedIndex == 0)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please Select Subjuct', ' Please Select Subjuct', 'Please Select Subjuct ')", true);
                return;
            }
            divFirst.Visible = false;
            divSecond.Visible = true;



       
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (disclaimer.Checked == false)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please check Terms & Conditions', 'Please check Terms & Conditions', 'Please check Terms & Conditions ')", true);
                return;
            }
            if (Session["Username"] != null)
            {
                string user = Session["Username"].ToString();
                DataSet ds = info.GetQuestions(Convert.ToInt32(DdlProgrm.SelectedValue));
                cmd1 = new SqlCommand("select isnull(max(ExamId)+1,1) from ExamHistory where Sid = '" + Convert.ToInt32(DdlProgrm.SelectedValue) + "' and StId ='" + Session["Username"].ToString() + "' ", con);
                con.Open();
                cmd1.CommandType = CommandType.Text;
                int j = Convert.ToInt32(cmd1.ExecuteScalar());
                Session["ExamId"] = j;
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Session["questionpaper"] = ds;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        cmd = new SqlCommand("insert into ExamHistory(Sid, StId, ExamId, Qid, CreatedDate, Ans, Choise) values ('" + Convert.ToInt32(DdlProgrm.SelectedValue) + "' , '" + user + "', '" + j + "',  '" + Convert.ToInt32(ds.Tables[0].Rows[i]["qid"]) + "', getdate(), '" + Convert.ToInt32(ds.Tables[0].Rows[i]["cans"]) + "' , 0) ", con);
                        cmd.CommandType = CommandType.Text;
                        cmd.ExecuteNonQuery();
                    }
                    con.Close();
                    Response.Redirect("Exam.aspx?p=" + Convert.ToInt32(DdlProgrm.SelectedValue));
                }
            }
            else
            {
                //logout page
            }
        }
    }
}
==================================================================

Result.aspx page code


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



<table style="width: 930px;border:1px dotted #808080;">

<tr>
<td class="style13">




    <asp:Image ID="Image1" runat="server" Height="331px" Width="293px"
        ImageUrl="~/img/result.jpg" /></td>
<td class="style12">


<table style="width: 426px" >
<tr>

<td class="style16">
    &nbsp;</td>
<td class="style15"> <tr>
            <td  align="left" class="style16">
                Student ID:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblID" runat="server" Text=""></asp:Label></td>
        </tr>
         <tr>
            <td align="left" class="style16">
                Subject:
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblSUb" runat="server" Text=""></asp:Label></td>
        </tr>
        
        
        <tr>
            <td align="left" class="style16">
                Starting Time :
            </td>
            <td align="left" class="style15">
                 <asp:Label ID="lblStart" runat="server" Text=""></asp:Label></td>
        </tr>
       
        <tr>
            <td align="left" class="style16">
                End Time :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblEnd" runat="server" Text=""></asp:Label></td>
        </tr>
       
                <tr>
            <td align="left" class="style16">
                No. of Questions :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblNoq" runat="server" Text=""></asp:Label></td>
        </tr>
       
                <tr>
            <td align="left" class="style16">
                Answered :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblAns" runat="server" Text=""></asp:Label></td>
        </tr>

        <tr>
            <td align="left" class="style16">
                Correct Answers :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblCans" runat="server" Text=""></asp:Label></td>
        </tr>
         <tr>
            <td align="left" class="style16">
                Un-Answered :
            </td>
            <td align="left" class="style15">
               <asp:Label ID="lblUnans" runat="server" Text=""></asp:Label></td>
        </tr>
        <tr>
            <td align="left" class="style16">
                Wrong :
            </td>
            <td align="left" class="style15">
              <asp:Label ID="lblWrong" runat="server" Text=""></asp:Label> </td>
        </tr>
         <tr>
            <td align="left" class="style16">
                Un-Answered :
            </td>
            <td align="left" class="style15">
               <asp:Label ID="Label3" runat="server" Text=""></asp:Label></td>
        </tr>
            <td align="left" class="style16">
             
            </td>
            <td align="left" class="style15">
               
                    <a href="" id ="Nav" runat="server">VIEW YOUR ANSWERS</a>
        </tr></td></tr></table>
        </td>
</tr></table>

</asp:Content>

=========================================================================================

Result.aspx.cs page code

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 Result : System.Web.UI.Page
    {        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        SqlDataAdapter adp;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
             DataSet ds2 = new DataSet();
            ds2 = (DataSet)Session["questionpaper"];
            adp = new SqlDataAdapter("select * from Exams left join Subjects on Exams.sid=Subjects.sid where  Exams.examid ='" + Convert.ToInt32(Request.QueryString["p"]) + "'", con);
            ds = new DataSet();
            adp.Fill(ds);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        lblID.Text=Session["Username"].ToString();
                        lblSUb.Text=(ds.Tables[0].Rows[0]["sname"]).ToString();
                        lblNoq.Text=(ds.Tables[0].Rows[0]["noq"]).ToString();
                        lblAns.Text=(ds.Tables[0].Rows[0]["Answered"]).ToString();
                        lblCans.Text=(ds.Tables[0].Rows[0]["nocans"]).ToString();
                        lblUnans.Text=(ds.Tables[0].Rows[0]["unans"]).ToString();
                        lblWrong.Text=(ds.Tables[0].Rows[0]["wrong"]).ToString();
                     
                        lblStart.Text = (Session["Stoptime"]).ToString();
                        lblEnd.Text = (Session["Etime"]).ToString();
                    }
                    Nav.HRef = "ViewPaper.aspx?id=" + Convert.ToInt32(ds.Tables[0].Rows[0]["ExamHistid"]);
            }
        }
    }
}
 =====================================================================


 


ViewPaper.aspx page code

<%@ Page Title="" Language="C#" MasterPageFile="~/MainPage.Master" AutoEventWireup="true" CodeBehind="ViewPaper.aspx.cs" Inherits="OnlineExam.ViewPaper" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
       
   <table>
<tr>
<td align="center">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/img/Excel-icon.png"
onclick="btnExcel_Click" Height="48px" Width="81px" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/img/word.png"
onclick="btnWord_Click" Height="50px" Width="77px" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails"
        AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
        Width="954px"  style="margin-right: 13px"
        onpageindexchanging="gvdetails_PageIndexChanging">
<RowStyle BackColor="#EFF3FB" />
    <Columns>
        <asp:TemplateField>
        <HeaderTemplate>
            <h2 style="width: 292px; margin-bottom: 0px">
                Review Questions</h2>
          
        </HeaderTemplate>
        <ItemTemplate>
       
         <pre style="color:Red;background-color:#eeeeee"><%# DataBinder.Eval(Container.DataItem, "question")%></pre>
            <pre>1.<%# DataBinder.Eval(Container.DataItem, "option1")%></pre>
            <pre>2.<%# DataBinder.Eval(Container.DataItem, "option2")%></pre>
            <pre>3.<%# DataBinder.Eval(Container.DataItem, "option3")%></pre>
            <pre>4.<%# DataBinder.Eval(Container.DataItem, "option4")%></pre>
            <pre>Correct Answer :<%# DataBinder.Eval(Container.DataItem, "Ans")%></pre>
            <pre>Your Answer    :<%# DataBinder.Eval(Container.DataItem, "Choise")%></pre>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</td>
</tr>
</table>
</asp:Content>

==========================================================================================

ViewPaper.aspx.cs page code

using System;
using System.Data;
using System.Configuration;
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.Data.SqlClient;
using System.Data;
using System.IO;

namespace OnlineExam
{
    public partial class ViewPaper : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (Session["UserName"] == null)
                    {
                        Response.Redirect("index.aspx");
                    }
                }
                catch
                {

                  
                }
                bindgrid();
            }



        }
        private void bindgrid()
        {
            SqlDataAdapter adp = new SqlDataAdapter("select * from ExamHistory left join Questions on ExamHistory.Qid = Questions.qid where   StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Request.QueryString["id"]) + "'   ", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                gvdetails.DataSource = ds;
                gvdetails.DataBind();
            }

        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        protected void btnExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvdetails.AllowPaging = false;
            gvdetails.DataBind();
            //Change the Header Row back to white color
            gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
            //Applying stlye to gridview header cells
            for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
            {
                gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
            }
            int j = 1;
            //This loop is used to apply stlye to cells based on particular row
            foreach (GridViewRow gvrow in gvdetails.Rows)
            {
                gvrow.BackColor = System.Drawing.Color.White;
                if (j <= gvdetails.Rows.Count)
                {
                    if (j % 2 != 0)
                    {
                        for (int k = 0; k < gvrow.Cells.Count; k++)
                        {
                            gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                        }
                    }
                }
                j++;
            }
            gvdetails.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        protected void btnWord_Click(object sender, ImageClickEventArgs e)
        {

            gvdetails.AllowPaging = false;
            gvdetails.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.doc"));
            Response.Charset = "";
            Response.ContentType = "application/ms-word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvdetails.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvdetails.PageIndex = e.NewPageIndex;
            bindgrid();
        }
    }
}