Sunday, June 30, 2013

using hidden field in asp.net | Example hidden variable in asp.net | hidden field state management

Below is example for using a hidden field in asp.net :

aspx code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input id="usrName" type="hidden" runat="server" />
    <asp:Button runat="server" Text="Show Value"/>
    </div>
    </form>
</body>
</html>

codebehind :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;

public partial class usingHiddenvariable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            usrName.Value = "chandan";
        }
        else
        {
            showHiddenValue();
        }

    }

    public void showHiddenValue()
    {
        Response.Write("<script language='javascript'>alert('Hidden value: "+ usrName.Value.ToString() +"');</script>");
    }
}

Result :


using output parameters in sql server procedures | output parameter example in sql server

Hi in this post i will show how to use output parameter in sql stored procedures:

Example :

select * from employee


Now using this above we will create a stored procedure where we will make use of output parameter.

CREATE PROCEDURE getEmpDetails @empDeptId INT
 ,@Name VARCHAR(50) OUTPUT
 ,@salary NUMERIC(18) OUTPUT
AS
BEGIN
 SELECT @Name = EmpName
  ,@salary = Salary
 FROM employee
 WHERE EmpDeptID = @empDeptId
END
GO


Testing :

DECLARE @EID INT
 ,@EName VARCHAR(50)
 ,@ESal NUMERIC(18)

SET @EID = 3

EXEC getEmpDetails @empDeptId = @EID
 ,@Name = @EName OUTPUT
 ,@salary = @ESal OUTPUT

SELECT @EName AS 'First Name'
 ,@ESal AS 'Last Name'

PRINT @Ename
PRINT @ESal




use of @@identity,scope_identity() and IDENT_CURRENT('') in sql server | Example Difference of @@identity,scope_identity() and IDENT_CURRENT('')

Difference between @@identity,scope_identity() and IDENT_CURRENT('')

1. @@identity :

select @@identity will return the last identity value generated for any table.

Example :
Suppose we have a table and we are inserting data into that table. And a trigger gets executed when any insert operation is done for that table. Then Select @@identity will return the last identity value generated for the table inside the trigger.

2. scope_identity()

select scope_identity() will return the last identity value generated for a table which is executed in the same scope i.e stored procedure, function, insert query.

Example :
Suppose we have a table and we are inserting data into that table. And a trigger gets executed when any insert operation is done for that table. Select scope_identity() will return the last identity value generated for the table in which the data is being inserted and not for the table inside the trigger.

3. IDENT_CURRENT('')

return the last identity value generated for the specific table .

Example:

1. Select IDENT_CURRENT('Employee')
2. Select IDENT_CURRENT('Department')



Monday, June 24, 2013

bind data to Repeater in asp.net | Repeater Example

hi in this post i will demonstrate on how to bind data to a Repeater in asp.net.

Aspx code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" Visible="true" runat="server">
            <HeaderTemplate>
             <table border="1" width="30%">
                    <tr>
                        <th>
                            Name
                        </th>
                        <th>
                            Salary
                        </th>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <%#DataBinder.Eval(Container.DataItem, "Name")%>
                    </td>
                    <td>
                        <%#DataBinder.Eval(Container.DataItem, "Salary")%>
                    </td>
                </tr>
            </ItemTemplate>
          
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

Codebehind:

 public void BindRepeater()
    {

        string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
        SqlConnection s1 = new SqlConnection(conStr);
        s1.Open();

        string queryString = "select empname as Name,salary from employee";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, s1);

        DataSet employee = new DataSet();
        adapter.Fill(employee, "employee");

        Repeater1.DataSource = employee.Tables[0];
        Repeater1.DataBind();

        s1.Close();

    }

Result :


using jquery .hover method in asp.net | Jquery hover Example | Jquery hover method demo

hi in this post i will show how to use a jquery .hover method in asp.net.
Using Jquery hover method a event is triggered when a mouse points to an element. i.e. label, button etc.

Below is the example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<html>
<head>
    <title></title>
</head>
<body>
    <div>
        <p>this is Jquery</p>
    </div>

    <script language="javascript" type="text/javascript">
$("p").hover(
  function () {
      $(this).append($("<span> and it is Awesome</span>"));
  },
  function () {
      $(this).find("span:last").remove();
  }
);
    </script>
</body>
</html>

Result :
1.

2. on hover i.e when mouse points to the element

Thursday, June 20, 2013

asp.net(C#) adding columns and rows for datatable in Codebehind | Example for adding rows, column manually in datatable from codebehind

hi in this post i will show how to manually add columns and rows in datatable from a codebehind page in asp.net (c#).

Below is the sample code for this :

public void createDatatable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Salary");

        DataRow firstRow = dt.NewRow();
        firstRow["Name"] = "Chandan";
        firstRow["Salary"] = "1000";

        dt.Rows.Add(firstRow);

        DataRow SecondRow = dt.NewRow();
        SecondRow["Name"] = "Subodh";
        SecondRow["Salary"] = "2000";

        dt.Rows.Add(SecondRow);

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Wednesday, June 19, 2013

Backup and restore database using a sql query in MS-SQL | Example of backup and restore of database in SQL

1. For backup use this below query

BACKUP DATABASE <Database_Name> TO DISK = 'D:\back\dbname.bak'

Make sure the folder has full rights in which we are going to save the .bak file or else you can get this below error:

Msg 3201, Level 16, State 1, Line 1
Cannot open backup device ''. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.


2. For Restoring a database use this below query 

Use MASTER 
GO
RESTORE DATABASE <Database_Name> FROM  DISK = N'D:\back\dbname.bak' WITH  FILE = 1,  KEEP_REPLICATION,  NOUNLOAD,  REPLACE,  STATS = 10
GO


Tuesday, June 18, 2013

check index fragmentation in sql server | Index Fragmentation Sql Query | Get Index Fragmentation Report

hi below is the code to get the fragmentation report in a database.

SELECT OBJECT_NAME(sindex.OBJECT_ID) AS TableName
,sindex.NAME AS CreatedIndexName
,ips.index_type_desc AS IndexType
,sindex.fill_factor AS Fill_Factor
,ips.fragment_count AS fragment_count
,ips.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) ips
INNER JOIN sys.indexes sindex ON sindex.object_id = ips.object_id
AND sindex.index_id = ips.index_id
ORDER BY ips.avg_fragmentation_in_percent DESC


For fragmentation more than 30 use Rebuild Index and for fragmentation between 5 to 30 use Reorganize index.

Examples:
ALTER INDEX ALL ON NORTHWND.dbo.Customers
REORGANIZE ; 
GO

ALTER INDEX ALL ON NORTHWND.dbo.Customers
REBUILD;
GO

ALTER INDEX ALL ON NORTHWND.dbo.Customers
REBUILD WITH (FILLFACTOR = 80);
GO

Note:
1. Rebuilding index happens online and offline. During Offline the database resources gets locked.
2. Reorganizing index always happens online.

Monday, June 17, 2013

Logic Fibonacci series | Fibonacci series in c#.net | Interview Questions Fibonacci sequence

hi below is the logic to get the Fibonacci sequence :

Logic:

 fibo(int n)
        {
            int a = 0;
            int b = 1;

            for (int i = 0; i <= n; i++)
            {
                int temp = a;
                a = b;
                b = temp + b;
                print(a);
            }
        }


C# Implementation :





Sunday, June 16, 2013

Struct and Class Example | Difference Between Struct and Class

Structs and Class:

struct class
1 It is value type It is Reference Type
2 Default access specifier is Public Default access specifier is Private
3 It only has Constructor It has both Constructor and Destructor
4 Struct has values residing on Stack  Class have Object values residing on Heap and it has references to the objects on stack
5 do not support Inheritance It Supports Inheritance

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    struct emp
    {
        public int empid;
        public string empname;
    }

    class dept
    {
        public int deptid;
        public string deptname;
    }

    class Program
    {
        static void Main(string[] args)
        {
            emp e = new emp();
            emp e2 = e;

            e.empid = 1;
            e.empname = "chandan";

            e2.empid = 2;
            e2.empname = "Rahul";

            Console.WriteLine("ID:{0} and Name:{1}", e.empid, e.empname);
            Console.WriteLine("ID2:{0} and Name2:{1}", e2.empid, e2.empname);

            dept d = new dept();
            dept d2 = d;

            d.deptid = 100;
            d.deptname = "Accounts";

            d2.deptid = 101;
            d2.deptname = "IT";

            Console.WriteLine("ID:{0} and Name:{1}", d.deptid, d.deptname);
            Console.WriteLine("ID2:{0} and Name2:{1}", d2.deptid, d2.deptname);

            Console.ReadLine();
        }
    }
}

Result :

class object referring to the same values whereas struct has new values assigned


Saturday, June 15, 2013

Using jQuery autocomplete plugin in asp.net | jQuery text autocomplete example ,tutorial

hi in this post i will show how to use a jQuery text autocomplete plugin in asp.net.

Example :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" language="javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript">
        $(function () {
            var availableTags = [
      "ARMADA",
      "ASTON MARTIN",
      "MAZDA",
      "FORD",
      "FERRARI",
      "LAMBORGINI",
      "MERC",
      "HYUNDAI",
      "HUMMER",
      "TATA",
      "RR",
      "TOYOTA",
      "MITSUBISHI",
      "VOLVO"
    ];
            $("#TextBox1").autocomplete({
                source: availableTags
            });
        });
    </script>
</head>
<body>
    <form runat="server">
    <asp:Label ID="Label1" runat="server" Text="Enter Text "></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>
</body>
</html>

Result :


Thursday, June 13, 2013

ADO.net | binding gridview using sqldatareader in asp.net(C#) | sqldatareader example in asp.net

hi in this post i will show how to bind a GridView using SqlDataReader in asp.net.

SqlDataReader read the records from the database on a row by row basis, which means as soon as a single record is fetched from the database it is returned Whereas in case of SqlDataAdapter the whole set of records are fetched and then returned. Thus SqlDataReader is a good choice if we have large amount of data to be shown in a grid.

Below is the code to bind grid view using SqlDataReader :

 void GetData()
    {
        string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
        SqlConnection s1 = new SqlConnection(conStr);
        s1.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = s1;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from company";
        SqlDataReader reader = cmd.ExecuteReader();
        GridView1.DataSource = reader;
        GridView1.DataBind();

        s1.Close();
    }


encrypt decrypt webconfig connectionStrings using visual studio command prompt in asp.net | Secure web config Connection Strings with RSACryptoServiceProvider Class in asp.net

hi in this post i will show how to encrypt decrypt webconfig connectionStrings with RSACryptoServiceProvider Class using visual studio command prompt in asp.net.

1. Go to Visual tools and select visual studio command prompt and run it as administrator.


2. Now to encrypt the connection string inside the web.config file.

use this below command

aspnet_regiis.exe -pef  "connectionStrings" "<application path>"



web.config


3. Now to decrypt the connection string inside the web.config.

use this below command

aspnet_regiis.exe -pdf  "connectionStrings" "<application path>"




web.config



Tuesday, June 11, 2013

[Resolved]Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken | Asp.net error resolution

Hi in this post i will show how to resolve this below error in asp.net:

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken......

1. To resolve this error go to start--> run -->cmd . Right click on cmd and select option run as administrator.



2. After this go to path "C:\Windows\Microsoft.NET\Framework\v4.0.30319" in the command prompt.



3. Now execute this command "aspnet_regiis.exe -iru".



Sunday, June 9, 2013

Using 'Indexof' and 'Substring' keywords in asp.net | String Methods 'IndexOf' and 'SubString' | IndexOf and Substring Example,


Hello in this post i will show the uses of  'IndexOf' and 'Substring' in asp.net

1. IndexOf : 

IndexOf provides the position of the Element or word.

if we have a string "Hello World" and we want know at what position
the "world" string starts.
'IndexOf' keyword will give the output as 6. So at 6th position the World word starts.

Syntax:

int i1;
i1 = s.IndexOf("World");

//output
//6


2. SubString:

Suppose we have a string like 'My Name is Alex Ferguson'. And from this string
i want only Alex word. Then here we can use Substring.

string s = "My Name is Alex Ferguson";
string s1 = s.Substring(12, 4);

//output
//Alex

Example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int i1,i2;
            string s1;
            string s = "Hello World";

            i1 = s.IndexOf("World");
            s1 = s.Substring(0, 5);
            i2 = s.Substring(0, 5).IndexOf("o");

            Console.WriteLine("Entered String: "+s);
            Console.WriteLine("\nPosition of 'World': "+i1);
            Console.WriteLine("\nSubString: " + s1);
            Console.WriteLine("\nPosition of 'o' in the Substring: " + i2);
            Console.ReadLine();
        }
    }
}


Result :





Friday, June 7, 2013

Export String to .txt File in asp.net | Exporting String Data to text

Hi in this post i will show how to export string data into a text file in asp.net.

Below is my sample code for this:

ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="stringToNotepad.aspx.cs" Inherits="stringToNotepad" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
        <asp:Button ID="Button1" runat="server" Text="Export to text(.txt)" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Codebehind:
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.Text;

public partial class stringToNotepad : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String s;
            s = "Hello World! This is C#.net";
            Label1.Text = s;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        Response.AddHeader("content-disposition", "attachment;filename=Note.txt");
        Response.ContentType = "application/vnd.text";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        Response.Write(Label1.Text.ToString());
        Response.End();
    }
}

Result:

1.

2.



Wednesday, June 5, 2013

Primary Key, Unique Key, Candidate Key, Foreign Key | Types of Keys in Sql Server

Types of Keys in Sql Server:

1. Primary Key : Primary Key is applied on a column to retrieve unique data from the table.
Hence it does not allow any duplicate values or null values in column.

2. Unique key : It is same as primary key just difference is that it will allow one null value in the column.

3. Candidate key : Candidate key can be applied on the columns or on set of columns which can retrieve unique data from the table. It resembles a primary key.

4. Foreign key : It is applied on a column which points to the primary key column from the other table. i.e values in the foreign key column should be the values from the primary key column of the other table.



Tuesday, June 4, 2013

Using of Message Contract in Asp.net WCF | Message Contract Example in asp.net | Using Message Contract along with Data Contract

hi in this post i will show and basic example of using message contract in WCF asp.net.

Message Contract : It is used to control the details inside the SOAP Header and Body.

Example:

1. This is how my solution explorer look like:

2. Interface code i.e. IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService5
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        EmpDetails GetDataUsingDataContract(EmpID EmpObj);
    }

    [DataContract]
    public class Employee
    {
        [DataMember(Name = "Name", Order = 1)]
        public string EmpName;

        [DataMember(Name = "Salary", Order = 2)]
        public string Salary;

    }

    [MessageContract(IsWrapped = false)]
    public class EmpID
    {
        [MessageHeader]
        public string Id;
    }

    [MessageContract(IsWrapped = false)]
    public class EmpDetails
    {
        [MessageBodyMember]
        public Employee Emp;
    }
}

3. Service1.svc.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService5
{
    public class Service1 : IService1
    {
        public EmpDetails GetDataUsingDataContract(EmpID EmpObj)
        {
            EmpDetails EmpDetailsObj = new EmpDetails();
            EmpDetailsObj.Emp = new Employee();

            if (EmpObj.Id == "0")
            {
                EmpDetailsObj.Emp.EmpName = "NA";
                EmpDetailsObj.Emp.Salary = "NA";
                return EmpDetailsObj;
            }
            else
            {
                EmpDetailsObj.Emp.EmpName = "Chandan";
                EmpDetailsObj.Emp.Salary = "10000";
                return EmpDetailsObj;
            }

        }
    }
}

4. Results:






Fault contract in WCF | Example of using fault contract in WCF asp.net | Handle Exceptions in WCF | Custom Error handling in WCF

Hi in this post i will show how to use fault contract in WCF to handle exceptions and how we can display a custom error message to client for the exception has occurred.

Taking a scenario where we have a divide by zero exception getting occurred . To that exception we can show a custom error message to the client as "Application Error has occurred. Please try again later" or we can also show the actual error generated by the .net application. To handle such an scenario we use Fault Contract.

Sample Code of WCF Service using Fault Contract to handle Exceptions:

1. Service Interface i.e IService2.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

[ServiceContract]
public interface IService2
{
    [OperationContract]
    [FaultContract(typeof(HandleException))]
    int GetData(int value, int value2);
}

[DataContract]
public class HandleException
{
    [DataMember]
    public string CustomExceptionMessage { get; set; }
    [DataMember]
    public string ErrorDesc { get; set; }
}


2. Consuming Interface into WCF .svc page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

public class Service2 : IService2
{
    public int GetData(int value, int value2)
    {
        HandleException Obj = new HandleException();
        try
        {
            return (value / value2);
        }
        catch (Exception ex)
        {
            Obj.CustomExceptionMessage = "An Application Error has occurred";
            Obj.ErrorDesc = ex.ToString();
            throw new FaultException<HandleException>(Obj, ex.ToString());
        }
    }
}


3. Consuming Service in my Client Application :
Here for the exception occurred in the service i will be showing the custom message in my client application which i have handled in the WCF Service catch block for every exception caused.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.ServiceModel;

public partial class FaultExceptionClient : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ServiceReference1.Service2Client s2 = new ServiceReference1.Service2Client();
            int Z = s2.GetData(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text));
            Response.Write("<script language='javascript'>alert('Result: " + Z + "');</script>");
        }
        catch (FaultException<ServiceReference1.HandleException> ex1)
        {
            lblErrorMessage.Visible = true;
            lblErrorMessage.Text = ex1.Detail.CustomExceptionMessage + "<br/>" + ex1.Detail.ErrorDesc;    
        }
    }
}

Result:



Sunday, June 2, 2013

Using Jquery Clone method in asp.net | Jquery Clone Example

Using Jquery clone Method we can create a duplicate element from the elements already present in the Html code.

Example: In this below Example on the button click i will duplicate the <div> content and display that duplicate <div> below the button.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryClone.aspx.cs" Inherits="JqueryClone" %>

<!DOCTYPE html>
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Button1").click(function () {
            $("#div1").clone().insertAfter("#Button1");
        });
    });
</script>
</head>
<body>

<div id="div1">Jquery is Awesomee !!</div>
<input id="Button1" type="button" value="button" />

</body>
</html>


Output:




Saturday, June 1, 2013

Save images in Database using Sql Query | Using OPENROWSET save Images in sql server database

Below is the sql query to save images from disk into the database :


CREATE TABLE EmployeeDetails(EmpPhoto image)
INSERT INTO EmployeeDetails(EmpPhoto)
SELECT * FROM
OPENROWSET(BULK N'C:\Users\chandansingh\Desktop\download.jpg', SINGLE_BLOB) cs

Bind Excel Data to Gridview in Asp.net | Excel to DataTable or Dataset c#

Hi in this post i will show how to bind data in excel to gridview in asp.net.

1. This is my Excel data. I will bind this below Excel data to grid


2. Using a OleDb Connection we will get the data from Excel and then bind that data to the GridView.

Below is the code:

<!--ASPX-->
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExcelToGrid.aspx.cs" Inherits="ExcelToGrid" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView> 
    </div>
    </form>
</body>
</html>



//CodeBehind :

using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;

public partial class ExcelToGrid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable Ds = GetDataFromExcel(@"C:\Users\chandan.singh\Desktop\Test.xls", "Sheet1");
        BindGrid(Ds);
    }

    public OleDbConnection GetExcelCon(string strFilePath)
    {
        OleDbConnection excelcon = new OleDbConnection();
        try
        {
            excelcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
                                                     "Data Source=" + strFilePath + ";Jet OLEDB:Engine Type=5;" +
                                                     "Extended Properties='Excel 8.0;IMEX=1;'");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return excelcon;
    }

    public DataTable GetDataFromExcel(string strFilePath, string SheetName)
    {
        DataTable dtCSV = new DataTable();
        try
        {
            OleDbConnection cnCSV = GetExcelCon(strFilePath);
            cnCSV.Open();
            OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [" + SheetName + "$]", cnCSV);
            OleDbDataAdapter daCSV = new OleDbDataAdapter();
            daCSV.SelectCommand = cmdSelect;
            daCSV.Fill(dtCSV);
            cnCSV.Close();
            daCSV = null;
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return dtCSV;
    }

    public void BindGrid(DataTable Ds)
    {
        GridView1.DataSource = Ds;
        GridView1.DataBind();
    }

}


3. Result: