Search...

Tuesday, April 17, 2012

Linq to DataTable different join operations in C#

Download Source code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace LinqToDataTable
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable Table1 = new DataTable();
            Table1.Columns.Add(new DataColumn("Id", Type.GetType("System.Int32")));
            Table1.Columns.Add(new DataColumn("Value", Type.GetType("System.String")));

            DataRow row = null;
            row = Table1.NewRow();
            row["Id"] = 1;
            row["Value"] = "First";
            Table1.Rows.Add(row);
            row = null;
            row = Table1.NewRow();
            row["Id"] = 2;
            row["Value"] = "Second";
            Table1.Rows.Add(row);
            row = null;
            row = Table1.NewRow();
            row["Id"] = 3;
            row["Value"] = "Third";
            Table1.Rows.Add(row);
            row = null;
            row = Table1.NewRow();
            row["Id"] = 4;
            row["Value"] = "Fourth";
            Table1.Rows.Add(row);
            row = null;
            row = Table1.NewRow();
            row["Id"] = 5;
            row["Value"] = "Fifth";
            Table1.Rows.Add(row);

            DataTable Table2 = new DataTable();
            Table2.Columns.Add(new DataColumn("Id", Type.GetType("System.Int32")));
            Table2.Columns.Add(new DataColumn("Value", Type.GetType("System.String")));

            row = null;
            row = Table2.NewRow();
            row["Id"] = 1;
            row["Value"] = "First";
            Table2.Rows.Add(row);
            row = null;
            row = Table2.NewRow();
            row["Id"] = 2;
            row["Value"] = "Second";
            Table2.Rows.Add(row);
            row = null;
            row = Table2.NewRow();
            row["Id"] = 3;
            row["Value"] = "Third";
            Table2.Rows.Add(row);
            row = null;
            row = Table2.NewRow();
            row["Id"] = 6;
            row["Value"] = "Six";
            Table2.Rows.Add(row);
            row = null;
            row = Table2.NewRow();
            row["Id"] = 7;
            row["Value"] = "Seven";
            Table2.Rows.Add(row);
            row = null;
            row = Table2.NewRow();
            row["Id"] = 8;
            row["Value"] = "Eight";
            Table2.Rows.Add(row);

            Console.WriteLine("---Inner join in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data = from table1 in Table1.AsEnumerable()
                       join table2 in Table2.AsEnumerable()
                       on table1.Field<Int32>("Id") equals table2.Field<Int32>("Id")
                       select new { Table1Id=table1.Field<Int32>("Id"),
                                    Table1Value = table1.Field<String>("Value"),
                                    Table2Id = table2.Field<Int32>("Id"),
                                    Table2Value = table2.Field<String>("Value")
                                  };

            foreach (var item in data)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                ,item.Table1Id
                                , item.Table1Value
                                , item.Table2Id
                                , item.Table2Value
                                );
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Left Join in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data1 = from table1 in Table1.AsEnumerable()
                        join table2 in Table2.AsEnumerable()
                        on table1.Field<Int32>("Id") equals table2.Field<Int32>("Id") into table1_table2
                        from items in table1_table2.DefaultIfEmpty()
                        select new
                        {
                            Table1Id = table1.Field<Int32>("Id"),
                            Table1Value = table1.Field<String>("Value"),
                            Table2Id = items == null ? 0 : items.Field<Int32>("Id"),
                            Table2Value = items == null ? "Null" : items.Field<String>("Value")
                        };

            foreach (var item in data1)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.Table1Id
                                , item.Table1Value
                                , item.Table2Id
                                , item.Table2Value
                                );
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Right Join in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data2 = from table2 in Table2.AsEnumerable()
                        join table1 in Table1.AsEnumerable()
                        on table2.Field<Int32>("Id") equals table1.Field<Int32>("Id") into table1_table2
                        from items in table1_table2.DefaultIfEmpty()
                        select new
                        {
                            Table1Id = items == null ? 0 : items.Field<Int32>("Id"),
                            Table1Value = items == null ? "Null" : items.Field<String>("Value"),
                            Table2Id = table2.Field<Int32>("Id"),
                            Table2Value = table2.Field<String>("Value")
                        };

            foreach (var item in data2)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.Table1Id
                                , item.Table1Value
                                , item.Table2Id
                                , item.Table2Value
                                );
            }


            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Outer Join in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data3 = (from table1 in Table1.AsEnumerable()
                         join table2 in Table2.AsEnumerable()
                         on table1.Field<Int32>("Id") equals table2.Field<Int32>("Id") into table1_table2
                         from table2 in table1_table2.DefaultIfEmpty()
                        //where table2 == null
                         select new { table1, table2 }
                        ).Concat(from table2 in Table2.AsEnumerable()
                                 join t1 in Table1.AsEnumerable()
                                 on table2.Field<Int32>("Id") equals t1.Field<Int32>("Id") into t1_t2
                                 from table1 in t1_t2.DefaultIfEmpty()
                                 where table1 == null
                                 select new { table1, table2 }
                        );

            foreach (var item in data3)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.table1 == null ? 0 : item.table1.Field<Int32>("Id")
                                , item.table1 == null ? "Null" : item.table1.Field<String>("Value")
                                , item.table2 == null ? 0 : item.table2.Field<Int32>("Id")
                                , item.table2 == null ? "Null" : item.table2.Field<String>("Value")
                                );
            }


            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Left Join where null in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data4 = from table1 in Table1.AsEnumerable()
                        join table2 in Table2.AsEnumerable()
                        on table1.Field<Int32>("Id") equals table2.Field<Int32>("Id") into table1_table2
                        from items in table1_table2.DefaultIfEmpty()
                        where items == null
                        select new
                        {
                            Table1Id = table1.Field<Int32>("Id"),
                            Table1Value = table1.Field<String>("Value"),
                            Table2Id = items == null ? 0 : items.Field<Int32>("Id"),
                            Table2Value = items == null ? "Null" : items.Field<String>("Value")
                        };

            foreach (var item in data4)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.Table1Id
                                , item.Table1Value
                                , item.Table2Id
                                , item.Table2Value
                                );
            }


            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Right Join where null in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data5 = from table2 in Table2.AsEnumerable()
                        join table1 in Table1.AsEnumerable()
                        on table2.Field<Int32>("Id") equals table1.Field<Int32>("Id") into table1_table2
                        from items in table1_table2.DefaultIfEmpty()
                        where items==null
                        select new
                        {
                            Table1Id = items == null ? 0 : items.Field<Int32>("Id"),
                            Table1Value = items == null ? "Null" : items.Field<String>("Value"),
                            Table2Id = table2.Field<Int32>("Id"),
                            Table2Value = table2.Field<String>("Value")
                        };

            foreach (var item in data5)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.Table1Id
                                , item.Table1Value
                                , item.Table2Id
                                , item.Table2Value
                                );
            }


            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Outer Join where null in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data6 = (from table1 in Table1.AsEnumerable()
                         join table2 in Table2.AsEnumerable()
                         on table1.Field<Int32>("Id") equals table2.Field<Int32>("Id") into table1_table2
                         from table2 in table1_table2.DefaultIfEmpty()
                         where table2 == null
                         select new { table1, table2 }
                        ).Concat(from table2 in Table2.AsEnumerable()
                                 join t1 in Table1.AsEnumerable()
                                 on table2.Field<Int32>("Id") equals t1.Field<Int32>("Id") into t1_t2
                                 from table1 in t1_t2.DefaultIfEmpty()
                                 where table1 == null
                                 select new { table1,table2}
                        );

            foreach (var item in data6)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.table1 == null ? 0 : item.table1.Field<Int32>("Id")
                                , item.table1==null? "Null":item.table1.Field<String>("Value")
                                , item.table2 == null ? 0 : item.table2.Field<Int32>("Id")
                                , item.table2 == null ? "Null" : item.table2.Field<String>("Value")
                                );
            }


            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Cross Join in DataTables.---");
            Console.WriteLine(Environment.NewLine);

            var data7 = from table1 in Table1.AsEnumerable()
                        from table2 in Table2.AsEnumerable()
                        select new { table1, table2 };
                     
            foreach (var item in data7)
            {
                Console.WriteLine("Table1 Id : {0}\tTable1 Value : {1}\tTable2 Id : {2}\tTable2 Value : {3}"
                                , item.table1.Field<Int32>("Id")
                                , item.table1.Field<String>("Value")
                                , item.table2.Field<Int32>("Id")
                                , item.table2.Field<String>("Value")
                                );
            }

            Console.Read();
        }
    }
}

/*******************************************************************************/

--Equivalent SQL Queryes

Go
Create database softwarekaffee

Go
Use softwarekaffee 

Go
Create table table1
(ID INT, Value VARCHAR(10))
INSERT INTO table1 (ID, Value)
Select 1,'First'
UNION ALL
Select 2,'Second'
UNION ALL
Select 3,'Third'
UNION ALL
Select 4,'Fourth'
UNION ALL
Select 5,'Fifth'
GO
Create table table2
(ID INT, Value VARCHAR(10))
INSERT INTO table2 (ID, Value)
Select 1,'First'
UNION ALL
Select 2,'Second'
UNION ALL
Select 3,'Third'
UNION ALL
Select 6,'Sixth'
UNION ALL
Select 7,'Seventh'
UNION ALL
Select 8,'Eighth'
GO
Select *
From table1
Select *
From table2

GO
/* INNER JOIN */
Select t1.*,t2.*
From table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID
GO
/* LEFT JOIN */
Select t1.*,t2.*
From table1 t1
LEFT JOIN table2 t2 ON t1.ID = t2.ID
GO
/* RIGHT JOIN */
Select t1.*,t2.*
From table1 t1
RIGHT JOIN table2 t2 ON t1.ID = t2.ID
GO
/* OUTER JOIN */
Select t1.*,t2.*
From table1 t1
FULL OUTER JOIN table2 t2 ON t1.ID = t2.ID
GO
/* LEFT JOIN - WHERE NULL */
Select t1.*,t2.*
From table1 t1
LEFT JOIN table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL
GO
/* RIGHT JOIN - WHERE NULL */
Select t1.*,t2.*
From table1 t1
RIGHT JOIN table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL
GO
/* OUTER JOIN - WHERE NULL */
Select t1.*,t2.*
From table1 t1
FULL OUTER JOIN table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL OR t2.ID IS NULL
GO
/* CROSS JOIN */
Select t1.*,t2.*
From table1 t1
CROSS JOIN table2 t2

Saturday, April 14, 2012

Linq to Datatable example in C#


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace LinqToDataTable
{
    class Program
    {
        static void Main(string[] args)
        {
            Random randomSalary = new Random();
            Random randomEmpCode = new Random();

            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(new DataColumn("Id",Type.GetType("System.Int32")));
            dataTable.Columns.Add(new DataColumn("EmployeeCode", Type.GetType("System.String")));
            dataTable.Columns.Add(new DataColumn("Salary", Type.GetType("System.Decimal")));

            DataRow row = null;
            for (int i = 1; i < 21; i++)
            {
                row = dataTable.NewRow();
                row["Id"] = i;
                row["EmployeeCode"] = String.Format("Emp{0}", randomEmpCode.Next(101, 201));
                row["Salary"] = randomSalary.Next(10000, 500000);
                dataTable.Rows.Add(row);
            }

            IEnumerable<DataRow> empdata = null;

            Console.WriteLine("---Reading all employee records.---");
            Console.WriteLine(Environment.NewLine);

            empdata= from employee in dataTable.AsEnumerable()
                                       select employee;

            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                ,item.ItemArray[0]
                                , item.ItemArray[1]
                                , item.ItemArray[2]);
            }

            /*
            //If you do not want to use ItemArray you can use Field.
            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                , item.Field<Int32>("Id")
                                , item.Field<String>("EmployeeCode")
                                , item.Field<Decimal>("Salary")
                                );
            }
             * */

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Reading employee record order by salary (ascending).---");
            Console.WriteLine(Environment.NewLine);

            empdata = from employee in dataTable.AsEnumerable()
                      orderby employee.Field<Decimal>("Salary") ascending
                      select employee;

            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                , item.ItemArray[0]
                                , item.ItemArray[1]
                                , item.ItemArray[2]);
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Reading employee record order by salary (ascending).---");
            Console.WriteLine(Environment.NewLine);

            empdata = from employee in dataTable.AsEnumerable()
                      orderby employee.Field<Decimal>("Salary") descending
                      select employee;

            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                , item.ItemArray[0]
                                , item.ItemArray[1]
                                , item.ItemArray[2]);
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Reading single record.---");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine("Enter id between 1 to 20.");
            Int32 id = Convert.ToInt32(Console.ReadLine());
            empdata = from employee in dataTable.AsEnumerable()
                      where employee.Field<Int32>("Id")==id
                      select employee;

            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                , item.ItemArray[0]
                                , item.ItemArray[1]
                                , item.ItemArray[2]);
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Reading selected columns.---");
            Console.WriteLine(Environment.NewLine);

            var records = from employee in dataTable.AsEnumerable()
                      where employee.Field<Int32>("Id") == id
                      select new { EmployeeId=employee.ItemArray[1],
                                   EmployeeSalary=employee.ItemArray[2]
                                 };
         
            foreach (var item in records)
            {
                Console.WriteLine("Employee Id : {0} | Salary : {1}"
                                , item.EmployeeId
                                , item.EmployeeSalary);
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Upade data in DataTable.---");
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Enter Id to update record.");
            Int32 idToUpdate = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter employee new salary.");
            Decimal salary = Convert.ToDecimal(Console.ReadLine());

            DataRow employeeRecord = dataTable.AsEnumerable().SingleOrDefault(q => q.Field<Int32>("Id") == idToUpdate);
            employeeRecord["Salary"] = salary;

            empdata = from employee in dataTable.AsEnumerable()
                      select employee;

            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                , item.ItemArray[0]
                                , item.ItemArray[1]
                                , item.ItemArray[2]);
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("---Delete data in DataTable.---");
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Enter Id to delete record.");
            Int32 idToDelete = Convert.ToInt32(Console.ReadLine());

            DataRow employeeToDelete = dataTable.AsEnumerable().SingleOrDefault(q => q.Field<Int32>("Id") == idToDelete);
            employeeToDelete.Delete();

            empdata = from employee in dataTable.AsEnumerable()
                      select employee;

            foreach (DataRow item in empdata)
            {
                Console.WriteLine("Id : {0}  | EmployeeCode : {1} | Salary : {2}"
                                , item.ItemArray[0]
                                , item.ItemArray[1]
                                , item.ItemArray[2]);
            }

            Console.Read();
        }
    }
}

Tuesday, April 10, 2012

Encryption and decryption of password in c#


using System;
using System.Security.Cryptography;
using System.IO;

namespace Encrypt_Decrypt
{
    class Program
    {
        static void Main(string[] args)
        {
            Program program=new Program();
            String encString = program.Encrypt("Your Password !", "3r%bh#ed");
            Console.WriteLine(encString);
            Console.WriteLine(program.Decrypt(encString, "3r%bh#ed"));
            Console.Read();
        }

        public string Encrypt(string strText, string strEncrypt)
        {
            // Convert strings into byte arrays.
            byte[] byKey = new byte[20];
            byte[] dv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                // Convert our plaintext into a byte array.
                // Let us assume that plaintext contains UTF8-encoded characters.
                byKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
                // Create DESCryptoServiceProvider object
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                // Convert our plaintext into a byte array.
                byte[] inputArray = System.Text.Encoding.UTF8.GetBytes(strText);
                // Define memory stream which will be used to hold encrypted data
                MemoryStream ms = new MemoryStream();
                // Define cryptographic stream (always use Write mode for encryption).
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, dv),
                    CryptoStreamMode.Write);
                // Start encrypting.
                cs.Write(inputArray, 0, inputArray.Length);
                // Finish encrypting.
                cs.FlushFinalBlock();
                // Convert encrypted data into a base64-encoded string and
                // Return encrypted string.
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string Decrypt(string strText, string strEncrypt)
        {
            // Convert strings into byte arrays.
            byte[] bKey = new byte[20];
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            try
            {
                // Convert our plaintext into a byte array.
                // Let us assume that plaintext contains UTF8-encoded characters.
                bKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
                // Create DESCryptoServiceProvider object
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                // Convert our plaintext into a byte array.
                Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText);
                // Define memory stream which will be used to hold encrypted data
                MemoryStream ms = new MemoryStream();
                // Define cryptographic stream (always use Write mode for encryption).
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write);
                // Start decrypting.
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                // Finish decrypting.
                cs.FlushFinalBlock();
                // Convert decrypted data into a string.
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                // Return decrypted string.
                return encoding.GetString(ms.ToArray());
            }

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

Saturday, April 7, 2012

Complete ListView example in Asp.Net c#



********************************************************************************

/*Add Stylesheet in your application names StyleSheet.css*/

 body {}

.Table
{
border-collapse: collapse;
border-spacing: 0;
font-family: Arial,Helvetica,Geneva,sans-serif;
font-size: 13px;
border:1px solid #e5e5e5;
width: 700px;
}

.Table th
{
border:0px;
background:#f5f5f5;
color:#444444;
text-align:center;
font-size:18px;
border:1px solid #e5e5e5;
}

.Table tr,td
{
    height:24px;
}

.Table tfoot td
{
background:#f5f5f5;
color:#444444;
text-align:center;
font-size:18px;
border:1px solid #e5e5e5;
}

.Table a
{
color:#005c9c;
}

.Table td
{
padding-left:10px;
border:1px solid #e5e5e5;
}

.altRow
{
background-color:#f8f8f8;
margin:2px 0px 0px 0px;
}

.TablePager
{
background:#f5f5f5;
color:#444444;
text-align:center;
font-size:18px;
border:1px solid #e5e5e5;
}

.button
{
background:#f5f5f5;
border:1px solid #cccccc;
border-radius:3px;
-moz-border-radius:3px; /* Firefox 3.6 and earlier */
-webkit-border-radius:3px; /* Chrome,Safari */
-o-border-radius:3px; /* opera */
}

div.pager
{
margin-top: 5px;
text-align:center;
background:#f5f5f5;
border:1px solid #e5e5e5;
margin:0px;
padding:2px;
width: 694px;
}

div.pager a
{
background:#f5f5f5;
padding: 2px 4px;
    display: inline-block;
    text-decoration: none;
    margin: auto 2px;
    color:#005c9c;
}

div.pager span span
{
    background:#f5f5f5;
    padding: 2px 4px;
    display: inline-block;
    margin: auto 2px;
}            

.first
{
    padding: 2px 4px;
    display: inline-block;
    margin: auto 2px;
}
             
.last
{
    padding: 2px 4px;
    display: inline-block;
    margin: auto 2px;
}
             
.current
{
color:#444444;
font-weight:bold;
text-decoration:underline;
}
             
.numeric
{
   color:#444444;
}

********************************************************************************

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

<!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>Complete ListView example in Asp.Net c#</title>
    <link href="Resources/StyleSheet/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListView ID="ListView1"
                    runat="server"
                    DataKeyNames="Id"
                    onitemcommand="ListView1_ItemCommand"
                    onitemcanceling="ListView1_ItemCanceling"
                    onitemdeleting="ListView1_ItemDeleting"
                    onitemediting="ListView1_ItemEditing"
                    oniteminserting="ListView1_ItemInserting"
                    onitemupdating="ListView1_ItemUpdating"
                    InsertItemPosition="FirstItem">
        <LayoutTemplate>
            <table class="Table">
            <thead>
            <tr>
            <th>Employee Name</th>
            <th>Salary</th>
            <th></th>
            </tr>
            </thead>
            <tbody>
                <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
            </tbody>
         
            </table>
        </LayoutTemplate>
     
        <ItemTemplate>
            <tr>
            <td><%# Eval("Employeename")%></td>
            <td><%# Eval("Salary")%></td>
            <td>
            <asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
            <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" OnClientClick="DeleteConfirmation();">Delete</asp:LinkButton>
            </td>
            </tr>
        </ItemTemplate>
     
        <AlternatingItemTemplate>
            <tr class="altRow">
            <td><%# Eval("Employeename")%></td>
            <td><%# Eval("Salary")%></td>
            <td>
            <asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
            <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" OnClientClick="DeleteConfirmation();">Delete</asp:LinkButton>
            </td>
            </tr>
        </AlternatingItemTemplate>
     
        <EditItemTemplate>
            <tr>
            <td><asp:TextBox ID="txtEmpName" runat="server" Text='<%# Eval("Employeename")%>'></asp:TextBox></td>
            <td><asp:TextBox ID="txtsalary" runat="server" Text='<%# Eval("Salary")%>'></asp:TextBox></td>
            <td>
                <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
                <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
            </td>
            </tr>
        </EditItemTemplate>
     
        <InsertItemTemplate>
            <tr>
            <td><asp:TextBox ID="txtEmpName" runat="server" Text='<%# Eval("Employeename")%>'></asp:TextBox></td>
            <td><asp:TextBox ID="txtsalary" runat="server" Text='<%# Eval("Salary")%>'></asp:TextBox></td>
            <td>
            <asp:Button ID="Button1" runat="server" Text="Insert" CommandName="Insert" CssClass="button"/>
            <asp:Button ID="Button2" runat="server" Text="Cancel" CommandName="Cancel" CssClass="button"/>
            </td>
            </tr>
        </InsertItemTemplate>
     
        </asp:ListView>
        <div class="pager">

        <asp:DataPager ID="DataPager1"
                       runat="server"
                       PagedControlID="ListView1"
                       OnPreRender="DataPager1_PreRender">

        <Fields>
        <asp:NextPreviousPagerField ShowFirstPageButton="false"
                                    ButtonType="Image"
                                    ShowPreviousPageButton="false"
                                    ShowLastPageButton="false"
                                    ShowNextPageButton="true"
                                    ButtonCssClass="first"
                                    NextPageImageUrl="~/Resources/StyleSheet/Images/prevArrow_ltr.gif"
                                    RenderNonBreakingSpacesBetweenControls="false" />

        <asp:NumericPagerField CurrentPageLabelCssClass="current"
                               NumericButtonCssClass="numeric"
                               ButtonCount="10"
                               RenderNonBreakingSpacesBetweenControls="false" />

        <asp:NextPreviousPagerField ShowFirstPageButton="false"
                                    ButtonType="Image"
                                    ShowPreviousPageButton="true"
                                    ShowLastPageButton="false"
                                    ShowNextPageButton="false"
                                    ButtonCssClass="last"
                                    PreviousPageImageUrl="~/Resources/StyleSheet/Images/nextArrow_ltr.gif"
                                    RenderNonBreakingSpacesBetweenControls="false" />

       </Fields>
       </asp:DataPager>
       </div>

    </div>
    </form>
</body>
</html>

<script type="text/javascript" language="javascript">
    function DeleteConfirmation() {
        if (confirm("Are you sure, you want to delete the selected records ?") == true)
            return true;
        else
            return false;
    }
 </script>

********************************************************************************

using System;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    private Employee employee;

    private delegate void BindEmployee();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmployee bindEmployee = new BindEmployee(BindData);
            bindEmployee();
        }
    }

    private void BindData()
    {
        employee = new Employee();
        ListView1.DataSource = employee.ReadAll();
        ListView1.DataBind();
    }

    protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        employee = new Employee();

        BindEmployee bindEmployee = new BindEmployee(BindData);
        Object id = null;
        try
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            id = ListView1.DataKeys[dataItem.DisplayIndex].Values[0];
        }
        catch
        { }

        String empName = String.Empty;
        String empSalary = String.Empty;

        switch (e.CommandName)
        {
            case "Insert":
                empName = ((TextBox)e.Item.FindControl("txtEmpName")).Text;
                empSalary = ((TextBox)e.Item.FindControl("txtsalary")).Text;
                employee = new Employee();
                employee.Employeename = empName;
                employee.Salary = Convert.ToDecimal(empSalary);
                employee.Create(employee);
                break;
            case "Update":
                empName = ((TextBox)e.Item.FindControl("txtEmpName")).Text;
                empSalary = ((TextBox)e.Item.FindControl("txtsalary")).Text;
                employee = new Employee();
                employee.Id = Convert.ToInt16(id);
                employee.Employeename = empName;
                employee.Salary = Convert.ToDecimal(empSalary);
                employee.UpdateById(employee);
                break;
            case "Delete":
                String empId = Convert.ToString(id);
                employee.DeleteById(empId);
                break;
            case "Cancel":
                ((TextBox)e.Item.FindControl("txtEmpName")).Text = "";
                ((TextBox)e.Item.FindControl("txtsalary")).Text = "";
                break;
        }
    }
    protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        BindEmployee bindEmployee = new BindEmployee(BindData);
        ListView1.EditIndex = e.NewEditIndex;
        bindEmployee();
    }
    protected void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        BindEmployee bindEmployee = new BindEmployee(BindData);
        ListView1.EditIndex = -1;
        bindEmployee();
    }
    protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        BindEmployee bindEmployee = new BindEmployee(BindData);
        ListView1.EditIndex = -1;
        bindEmployee();
    }
    protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        BindEmployee bindEmployee = new BindEmployee(BindData);
        ListView1.EditIndex = -1;
        bindEmployee();
    }
    protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        BindEmployee bindEmployee = new BindEmployee(BindData);
        ListView1.EditIndex = -1;
        bindEmployee();
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        BindEmployee bindEmployee = new BindEmployee(BindData);
        bindEmployee();
    }
}

********************************************************************************

using System;
using System.Web.Configuration;
public class Connection
{
public Connection(){}
     /// <summary>
     /// Get Connection string.
     /// <summary>
  public static String Cs
    {
        get
        {
            return WebConfigurationManager.ConnectionStrings["cs"].ConnectionString;
        }
    }
}


********************************************************************************

#region Namespaces
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
#endregion

/// <summary>
/// class Employee
/// </summary>
 public class Employee
 {
#region Properties
      private Int32 _Id;
     /// <summary>
     ///Gets or Sets the Int32 value of Id
     /// </summary>
      public Int32 Id { get { return _Id;} set { _Id = value;} }

      private String _Employeename;
     /// <summary>
     ///Gets or Sets the String value of Employeename
     /// </summary>
      public String Employeename { get { return _Employeename;} set { _Employeename = value;} }

      private Decimal _Salary;
     /// <summary>
     ///Gets or Sets the Decimal value of Salary
     /// </summary>
      public Decimal Salary { get { return _Salary;} set { _Salary = value;} }

#endregion

#region Private Meambers
      private SqlCommand cmd;
      private SqlConnection con;
      private SqlDataReader table;
      private String ConnectionString = String.Empty;
#endregion

#region Constructor
     /// <summary>
     ///Default constructor
     /// </summary>
      public Employee()
      {
        ConnectionString=Connection.Cs;
      }

     /// <summary>
     ///Parameterised constructor
     /// </summary>
      public Employee(String connectionString)
      {
        ConnectionString=connectionString;
      }
#endregion

#region Public Methods

      /// <summary>
      /// This meathod is for inserting record in Employee table.
      /// </summary>
      /// <param name="object of Employee"></param>
      /// <returns>Number of row affected by query.</returns>

      public Int32 Create(Employee obj)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Insert Into [dbo].[Employee]([Employeename],[Salary]) Values(@Employeename,@Salary)", con);
                  cmd.Parameters.AddWithValue("@Employeename", obj._Employeename);
                  cmd.Parameters.AddWithValue("@Salary", obj._Salary);
                  return cmd.ExecuteNonQuery();
              }
              finally
              {
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
                  cmd.Parameters.Clear();
              }
          }
      }

     /// <summary>
     /// This meathod returns all records of Employee table.
     /// </summary>
     /// <returns> All rows of Employee table.</returns>


      public List<Employee> ReadAll()
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Employee> list = new List<Employee>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select Top(1000)* From [dbo].[Employee]",con);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Employee obj = new Employee();
                obj._Id = table.GetInt32(0);
                obj._Employeename = table.GetString(1);
                obj._Salary = table.GetDecimal(2);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

      public Int32 UpdateById(Employee obj)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Update [dbo].[Employee] Set [Employeename] = @Employeename,[Salary] = @Salary Where [Id] =@Id", con);
                  cmd.Parameters.AddWithValue("@Employeename", obj._Employeename);
                  cmd.Parameters.AddWithValue("@Salary", obj._Salary);
                  cmd.Parameters.AddWithValue("@Id", obj._Id);
                  return cmd.ExecuteNonQuery();
              }
              finally
              {
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
                  cmd.Parameters.Clear();
              }
          }
      }

      /// <summary>
      /// This meathod is for deleting records in Employee table by column Id.
      /// </summary>
      /// <param name="Id" ></param>
      /// <returns>Number of row affected by query.</returns>

      public Int32 DeleteById(String id)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Delete From [dbo].[Employee] Where [Id] =@Id", con);
                  cmd.Parameters.AddWithValue("@Id", id);
                  return cmd.ExecuteNonQuery();
              }
              finally
              {
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
                  cmd.Parameters.Clear();
              }
          }
      }
#endregion

 }

********************************************************************************

<connectionStrings>
<add name="cs" connectionString="Data Source=Your Data Source;Initial Catalog=softwarekaffee;Persist Security Info=True;User ID=Your User Id;Password=Your Password"/>
</connectionStrings>

********************************************************************************

Go
Create database softwarekaffee

Go
use softwarekaffee

Go
create table Employee
(
Id int identity primary key,
EmployeeName nvarchar(30),
Salary decimal(7,2)
)

Insert Into Employee Values ('Kaushik',41000);
Insert Into Employee Values ('Rahul',25000);
Insert Into Employee Values ('Sumit',26000);
Insert Into Employee Values ('Ravi',40000);
Insert Into Employee Values ('Rajeev',41000);
Insert Into Employee Values ('Amit',25000);
Insert Into Employee Values ('Gautam',26000);
Insert Into Employee Values ('Ranveer',40000);
Insert Into Employee Values ('Devendra',40000);
Insert Into Employee Values ('Sunil',40000);
Insert Into Employee Values ('Manas',41000);
Insert Into Employee Values ('Mishri Lal',25000);
Insert Into Employee Values ('Avinash',26000);
Insert Into Employee Values ('Alok',40000);
Insert Into Employee Values ('Pooja',41000);
Insert Into Employee Values ('Geeta',25000);
Insert Into Employee Values ('Lalita',26000);
Insert Into Employee Values ('Meenakshi',40000);
Insert Into Employee Values ('Rajendra',40000);
Insert Into Employee Values ('Sunita',40000);
Insert Into Employee Values ('Sandeep',26000);
Insert Into Employee Values ('Vinod',40000);
Insert Into Employee Values ('Remo',40000);

********************************************************************************