Wednesday, February 29, 2012

Awesome GridView Css


Download



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

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

 body {}
.gridView{width:100%;background:#ffffff;border:1px solid #476db6; border-collapse:separate;}
.gridView th{border:0px;background:url('Images/hfbg.jpg') repeat-x;color:#ffffff;text-align:center;font-size:18px;}
.gridView td{padding-left:10px;border:1px solid #b5b5b5}

.altRow{background:url('Images/alt.png') repeat-x}

.gridPager{background:url('Images/hfbg.jpg') repeat-x;text-align:center;}
.gridPager table{margin:0px auto;}
.gridPager table td{width:25px;border:0px;}
.gridPager table span{cursor:pointer;font-weight:bold;color:#ffffff;}
.gridPager table a{cursor:pointer;text-decoration:none;color:#ffffff;}
.gridPager table a:hover{text-decoration:underline;}
.gridPager:hover{background:url('Images/hfbg.jpg') repeat-x;text-align:center;}

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

<%@ 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>Awesome GridView Css</title>
    <link href="Resources/StyleSheet/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <b>
        <%="You are viewing page "+(GridView1.PageIndex+1)+" of "+GridView1.PageCount+" ,row count "+GridView1.Rows.Count %>
        </b>
        <asp:GridView ID="GridView1"
        runat="server"
        AutoGenerateColumns="false"
        DataKeyNames="Id,Department_id"
        CssClass="gridView"
        AlternatingRowStyle-CssClass="altRow"
        PagerStyle-CssClass="gridPager"
        AllowPaging="true"
        PageSize="15"
        onpageindexchanging="GridView1_PageIndexChanging"
        onrowdatabound="GridView1_RowDataBound">
        <Columns>
        <asp:BoundField DataField="Employeename" HeaderText="Employee Name" />
        <asp:BoundField DataField="Salary" HeaderText="Salary" />
        <asp:BoundField DataField="Department_id" HeaderText="Department Name" />
        </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

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

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

public partial class _Default : System.Web.UI.Page
{
    private Employee employee = new Employee();
    private Department department = new Department();
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.CellSpacing = -1;
        BindGrid();
    }

    private void BindGrid()
    {
        GridView1.DataSource = employee.ReadAll();
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        GridViewRow currentRow = e.Row;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
                String departmentName = currentRow.Cells[2].Text;
                currentRow.Cells[2].Text = department.ReadAllById(currentRow.Cells[2].Text)[0].Departmentname;
            }
            catch
            {
            }
        }
    }
}

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

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 Department
/// </summary>
 public class Department
 {
#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 _Departmentname;
     /// <summary>
     ///Gets or Sets the String value of Departmentname
     /// </summary>
      public String Departmentname { get { return _Departmentname;} set { _Departmentname = 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 Department()
      {
        ConnectionString=Connection.Cs;
      }

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

#region Public Methods

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


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

     /// <summary>
     /// This meathod returns all records of Department table by column Id.
     /// </summary>
     /// <param name="Id"></param>
     /// <returns>All rows of Department table.</returns>


      public List<Department> ReadAllById(String id)
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Department> list = new List<Department>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select * From [dbo].[Department] Where [Id]=@ID",con);
            cmd.Parameters.AddWithValue("@Id",id);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Department obj = new Department();
                obj._Id = table.GetInt32(0);
                obj._Departmentname = table.GetString(1);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

#endregion

 }

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

#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;} }

      private Int32 _Department_id;
     /// <summary>
     ///Gets or Sets the Int32 value of Department_id
     /// </summary>
      public Int32 Department_id { get { return _Department_id;} set { _Department_id = 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 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);
                obj._Department_id = table.GetInt32(3);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

      /// <summary>
      /// This meathod returns all records of Employee table by column Department_id.
      /// </summary>
      /// <param name="Department_id" ></param>
      /// <returns>All rows of Employee table.</returns>


      public List<Employee> ReadAllEmployeeByDepartment_id(String department_id)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  List<Employee> list = new List<Employee>();
                  con = new SqlConnection(ConnectionString);
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Select * From [dbo].[Employee] where [Department_id]=@Department_id", con);
                  cmd.Parameters.AddWithValue("@Department_id", department_id);
                  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);
                          obj._Department_id = table.GetInt32(3);
                          list.Add(obj);
                      }
                      //return (list.Count > 0) ? list : GetEmptyList(list);
                      return list;
                  }
              }
              finally
              {
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
              }
          }
      }

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


      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,[Department_id] = @Department_id Where [Id] =@Id",con);
           cmd.Parameters.AddWithValue("@Employeename",obj._Employeename);
           cmd.Parameters.AddWithValue("@Salary",obj._Salary);
           cmd.Parameters.AddWithValue("@Department_id",obj._Department_id);
           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 Department
(
Id int identity primary key,
DepartmentName nvarchar(30)
)
Insert Into Department Values ('Sales');
Insert Into Department Values ('Production');
Insert Into Department Values ('Purchase');
Insert Into Department Values ('Stock');

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

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


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

Configuring services with endpoints


Download


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


using System;
using System.Runtime.Serialization;

namespace EvalService
{
    [DataContract]
    public class Eval
    {
        [DataMember]
        public String Id { get; set; }
        [DataMember]
        public String Submitter { get; set; }
        [DataMember]
        public String Comments { get; set; }
        [DataMember]
        public DateTime TimeSubmitted { get; set; }
    }
}

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


using System;
using System.Collections.Generic;

namespace EvalService
{

    public class EvalService:IEvalService
    {
        private List<Eval> list = new List<Eval>();
        #region IEvalService Members

        public void SubmitEval(Eval eval)
        {
            Eval evalObj = new Eval();
            evalObj.Id = Guid.NewGuid().ToString();
            evalObj.Submitter = eval.Submitter;
            evalObj.Comments = eval.Comments;
            evalObj.TimeSubmitted = DateTime.Now;
            list.Add(evalObj);
        }

        public List<Eval> GetEvals()
        {
            return list;
        }

        public void RemoveEval(string id)
        {
            list.Remove(list.Find(q => q.Id.Equals(id)));
        }

        #endregion
    }
}

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


using System;
using System.Collections.Generic;
using System.ServiceModel;

namespace EvalService
{
    [ServiceContract]
    public interface IEvalService
    {
        [OperationContract]
        void SubmitEval(Eval obj);
        [OperationContract]
        List<Eval> GetEvals();
        [OperationContract]
        void RemoveEval(String id);
    }
}


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


<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="EvalService.ServiceBehavior1"
        name="EvalService.EvalService">
        <endpoint address="ws" binding="wsHttpBinding" contract="EvalService.IEvalService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
       
        <!--Default Bianding it helps other end points to exchange metadata-->
        <endpoint address="mex"
 binding="mexHttpBinding"
 contract="IMetadataExchange" />

<!--basicHttoBinding-->
        <endpoint address="basic"
 binding="basicHttpBinding"
 bindingConfiguration=""
          contract="EvalService.IEvalService" />

<!--netTcpBinding-->
        <endpoint address="net.tcp://localhost:8888/evalservice"
 binding="netTcpBinding"
          bindingConfiguration=""
 contract="EvalService.IEvalService" />

<!--netNamedPipeBinding-->
        <endpoint address="net.pipe://localhost/evalservice"
 binding="netNamedPipeBinding"
          bindingConfiguration=""
 contract="EvalService.IEvalService" />

        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/evalservice" />
          </baseAddresses>
        </host>

      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="EvalService.ServiceBehavior1">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>


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




Tuesday, February 28, 2012

Serialize & De-serialize your business objects to data file



using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ObjectToDatabase
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new Employee object
            Employee employee = new Employee();
            employee.EmpId = 1;
            employee.EmpName = "Kaushik Kumar Mistry";

            Stream stream = File.Open("EmployeeInfo.dat", FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();

            Console.WriteLine("Writing Employee Information to EmployeeInfo.dat file.");
            bformatter.Serialize(stream, employee);
            stream.Close();

            //Open the file written above and read values from it.
            stream = File.Open("EmployeeInfo.dat", FileMode.Open);
            bformatter = new BinaryFormatter();

            Console.WriteLine("Reading Employee Information from EmployeeInfo.dat file.");
            employee = (Employee)bformatter.Deserialize(stream);
            stream.Close();

            Console.WriteLine("Employee Id: {0}", employee.EmpId.ToString());
            Console.WriteLine("Employee Name: {0}", employee.EmpName);
            Console.ReadKey();
        }
    }

    [Serializable]
    public class Employee : ISerializable
    {
        public int EmpId{get;set;}
        public string EmpName { get; set; }

        //Default constructor.
        public Employee()
        {
        }

        //Deserialization constructor.
        public Employee(SerializationInfo info, StreamingContext ctxt)
        {
            EmpId = (int)info.GetValue("EmployeeId", typeof(int));
            EmpName = (String)info.GetValue("EmployeeName", typeof(string));
        }

        //Serialization function.
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            info.AddValue("EmployeeId", EmpId);
            info.AddValue("EmployeeName", EmpName);
        }
    }
}

Sunday, February 26, 2012

Send mail with multiple file attachments using Gmail in Asp.Net




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

<%@ 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>
    <title>Send mail with multiple file attachments using Gmail in Asp.Net</title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<p>To:</p>
<p>
<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
</p>
<p>Subject:</p>
<p>
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
</p>
<p>Message Body:</p>
<p>
<asp:TextBox ID="txtMsgBody" runat="server" TextMode="MultiLine" Columns="80" Rows="10"></asp:TextBox>
</p>
<p>
Attachment:
</p>
<p id="upload-area">
   <input id="File1" type="file" runat="server" size="60" />
</p>
<p>
<a href="#" onclick="addTypeFile()">Attach another file</a>
</p>
<p><asp:Button ID="btnSubmit" runat="server" Text="Send" OnClick="btnSubmit_Click" /></p>
<span id="Span1" runat="server" />

<script type="text/javascript">
    function addTypeFile() {
        if (!document.getElementById || !document.createElement)
            return false;

        var uploadArea = document.getElementById("upload-area");

        if (!uploadArea)
            return;

        var newLine = document.createElement("br");
        uploadArea.appendChild(newLine);

        var newTypeFile = document.createElement("input");
        newTypeFile.type = "file";
        newTypeFile.size = "60";

        if (!addTypeFile.lastAssignedId)
            addTypeFile.lastAssignedId = 100;

        newTypeFile.setAttribute("id", "file1" + addTypeFile.lastAssignedId);
        newTypeFile.setAttribute("name", "file1:" + addTypeFile.lastAssignedId);
        uploadArea.appendChild(newTypeFile);
        addTypeFile.lastAssignedId++;
    }
</script>
</form>
</body>
</html>

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


using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Web;

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

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            List<Attachment> attachment = new List<Attachment>();
            HttpFileCollection uploads = HttpContext.Current.Request.Files;
            for (int i = 0; i < uploads.Count; i++)
            {

                if (uploads[i].FileName.Length == 0)
                    continue;
                attachment.Add(new Attachment(uploads[i].InputStream, uploads[i].FileName));
            }
            MailSender.SendMail(txtTo.Text, txtSubject.Text, txtMsgBody.Text, attachment);
            Span1.InnerHtml = "Mail send successfully." ;
        }
        catch (Exception ex)
        {
            Span1.InnerHtml = ex.Message;
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;


public class MailSender
{
    public MailSender() { }
  
    /// <summary>
    /// Send mail with attachments from your gmail id.
    /// </summary>
    /// <param name="to"></param>
    /// <param name="subject"></param>
    /// <param name="messageBody"></param>
    /// <param name="attachment"></param>
    /// <returns></returns>
    public static bool SendMail(String to, String subject, String messageBody, List<Attachment> attachmentCollection)
    {
        try
        {
            NetworkCredential networkCredential = new NetworkCredential("YourEmailId@gmail.com", "YourPassword");
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(networkCredential.UserName);
            mailMessage.To.Add(new MailAddress(to));
            mailMessage.Subject = subject;
            mailMessage.Body = messageBody;
            mailMessage.IsBodyHtml = true;

            foreach (Attachment attachment in attachmentCollection)
            {
                mailMessage.Attachments.Add(attachment);
            }
            
            mailMessage.Priority = MailPriority.High;
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
            //smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = networkCredential;
            smtpClient.Send(mailMessage);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}



Serialize & De-serialize your business objects to XML

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace SerializeToXML
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie movie = new Movie();
            movie.Title = "Ghost Rider 2";
            movie.ReleaseDate = DateTime.Parse("24/Feb/2012");
            movie.Rating = 4.2f;

            List<Movie> list = new List<Movie>() { movie};
            movie.SerializeToXML(list);
            var data =movie.DeserializeFromXML();
            foreach(var x in data)
            {
                Console.WriteLine(x.Title+" "+x.Rating+" "+x.ReleaseDate);
            }
            Console.ReadLine();
        }
    }

    public class Movie
    {
        [XmlAttribute("MovieName")]
        public string Title{ get; set; }
        [XmlElement("MovieRating")]
        public float Rating{ get; set; }
        [XmlElement("MovieReleaseDate")]
        public DateTime ReleaseDate{ get; set; }

        public void SerializeToXML(List<Movie> movies)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Movie>));
            TextWriter textWriter = new StreamWriter(@"d:\movie.xml");
            serializer.Serialize(textWriter, movies);
            textWriter.Close();
        }

        public List<Movie> DeserializeFromXML()
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
            TextReader textReader = new StreamReader(@"d:\movie.xml");
            List<Movie> movies;
            movies = (List<Movie>)deserializer.Deserialize(textReader);
            textReader.Close();
            return movies;
        }
    }
}

Friday, February 24, 2012

Gridview inside a GridView



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


/*Add Stylesheet in your application names StyleSheet.css*/
body {}
.gridView{width:100%;background:#ffffff;border:1px solid #476db6; border-collapse:separate;}
.gridView th{border:0px;background:#a7b7fe;color:#000000;text-align:center;font-size:18px;}
.gridView td{border:0px;padding-left:10px;}
.altRow{background:#d1daff;}
.gridPager{background:#a7b7fe;color:#000000;}
.gridPager table{margin:0px auto;}
.gridPager table td{width:20px;}
.gridPager table span{cursor:pointer;font-weight:bold;color:#1a1ac9;}
.gridPager table a{cursor:pointer;text-decoration:none;color:#000000;}
.gridPager table a:hover{text-decoration:underline;}


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

<%@ 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 id="Head1" runat="server">
    <title>Gridview inside a GridView</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>

     <asp:GridView ID="OuterGrid"
        runat="server"
        DataKeyNames="Id"
        AutoGenerateColumns="false"
        CssClass="gridView"
        AlternatingRowStyle-CssClass="altRow"
        PagerStyle-CssClass="gridPager" onrowdatabound="OuterGrid_RowDataBound"
        >
    <Columns>
        <asp:TemplateField HeaderText="Department Name">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Departmentname") %>' />
        </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField>
        <ItemTemplate>
            <asp:GridView ID="InnerGrid"
            runat="server"
            AutoGenerateColumns="false"
            CssClass="gridView"
            AlternatingRowStyle-CssClass="altRow">
            <Columns>
            <asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" />
            <asp:BoundField DataField="Salary" HeaderText="Salary" />
            </Columns>
            </asp:GridView>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    </asp:GridView>
</div>
    </form>
</body>
</html>

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

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindOuterGrid();
        }
        OuterGrid.CellSpacing = 1;
    }
    
    public void BindOuterGrid()
    {
        Department department = new Department();
        OuterGrid.DataSource = department.ReadAll();
        OuterGrid.DataBind();
    }
    protected void OuterGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Employee employee = new Employee();
            GridViewRow currentRow = e.Row;
            String dataKey=OuterGrid.DataKeys[currentRow.RowIndex].Value.ToString();
            
            GridView innerGrid = (GridView)currentRow.Cells[1].FindControl("InnerGrid");
            innerGrid.DataSource = employee.ReadAllEmployeeByDepartment_id(dataKey);
            innerGrid.DataBind();
            innerGrid.CellSpacing = 1;
        }
    }
}

********************************************************************************
/*  Connection Class*

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;
        }
    }
}

********************************************************************************
/* Department Class*/

#region Namespaces

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
#endregion

/// <summary>
/// class Department
/// </summary>
 public class Department
 {
#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 _Departmentname;
     /// <summary>
     ///Gets or Sets the String value of Departmentname
     /// </summary>
      public String Departmentname { get { return _Departmentname;} set { _Departmentname = 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 Department()
      {
        ConnectionString=Connection.Cs;
      }

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

#region Public Methods

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


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

     /// <summary>
     /// This meathod returns all records of Department table by column Id.
     /// </summary>
     /// <param name="Id"></param>
     /// <returns>All rows of Department table.</returns>


      public List<Department> ReadAllById(String id)
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Department> list = new List<Department>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select * From [dbo].[Department] Where [Id]=@ID",con);
            cmd.Parameters.AddWithValue("@Id",id);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Department obj = new Department();
                obj._Id = table.GetInt32(0);
                obj._Departmentname = table.GetString(1);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

#endregion

 }

*********************************************************************************
/*Employee Class*/

#region Namespaces

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
#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;} }

      private Int32 _Department_id;
     /// <summary>
     ///Gets or Sets the Int32 value of Department_id
     /// </summary>
      public Int32 Department_id { get { return _Department_id;} set { _Department_id = 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 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);
                obj._Department_id = table.GetInt32(3);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

      /// <summary>
      /// This meathod returns all records of Employee table by column Department_id.
      /// </summary>
      /// <param name="Department_id" ></param>
      /// <returns>All rows of Employee table.</returns>


      public List<Employee> ReadAllEmployeeByDepartment_id(String department_id)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  List<Employee> list = new List<Employee>();
                  con = new SqlConnection(ConnectionString);
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Select * From [dbo].[Employee] where [Department_id]=@Department_id", con);
                  cmd.Parameters.AddWithValue("@Department_id", department_id);
                  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);
                          obj._Department_id = table.GetInt32(3);
                          list.Add(obj);
                      }
                      //return (list.Count > 0) ? list : GetEmptyList(list);
                      return list;
                  }
              }
              finally
              {
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
              }
          }
      }

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


      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,[Department_id] = @Department_id Where [Id] =@Id",con);
           cmd.Parameters.AddWithValue("@Employeename",obj._Employeename);
           cmd.Parameters.AddWithValue("@Salary",obj._Salary);
           cmd.Parameters.AddWithValue("@Department_id",obj._Department_id);
           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=sa;Password=Your Password"/>
</connectionStrings>

********************************************************************************* 
/*Database Schema*/

Go
Create database softwarekaffee

Go
use softwarekaffee 

Go
create table Department
(
Id int identity primary key,
DepartmentName nvarchar(30)
)
Insert Into Department Values ('Sales');
Insert Into Department Values ('Production');
Insert Into Department Values ('Purchase');
Insert Into Department Values ('Stock');

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

Insert Into Employee Values ('Kaushik',41000,1);
Insert Into Employee Values ('Rahul',25000,2);
Insert Into Employee Values ('Sumit',26000,3);
Insert Into Employee Values ('Ravi',40000,4);
Insert Into Employee Values ('Rajeev',41000,1);
Insert Into Employee Values ('Amit',25000,2);
Insert Into Employee Values ('Gautam',26000,3);
Insert Into Employee Values ('Ranveer',40000,4);
Insert Into Employee Values ('Devendra',40000,4);
Insert Into Employee Values ('Sunil',40000,4);

GridView Edit,Update,Delete And Bind DropdownList in RowEditing event.




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


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

body {}
.gridView{width:100%;background:#ffffff;border:1px solid #476db6; border-collapse:separate;}
.gridView th{border:0px;background:#a7b7fe;color:#000000;text-align:center;font-size:18px;}
.gridView td{border:0px;padding-left:10px;}
.gridView tr:hover{cursor:pointer; background:#ffff00;}
.gridView tr:last-child:hover{ background:#000;background:#a7b7fe;}
.altRow{background:#d1daff;}
.gridPager{background:#a7b7fe;color:#000000;}
.gridPager table{margin:0px auto;}
.gridPager table td{width:20px;}
.gridPager table span{cursor:pointer;font-weight:bold;color:#1a1ac9;}
.gridPager table a{cursor:pointer;text-decoration:none;color:#000000;}
.gridPager table a:hover{text-decoration:underline;}


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

<%@ 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>GridView Edit,Update,Delete And Bind DropdownList in RowEditing event.</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <%="You are viewing page "+(GridView1.PageIndex+1)+" of "+GridView1.PageCount+" ,row count "+GridView1.Rows.Count %>
        <asp:GridView ID="GridView1"
        runat="server"
        AutoGenerateColumns="false"
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        DataKeyNames="Id,Department_id"
        CssClass="gridView"
        AlternatingRowStyle-CssClass="altRow"
        PagerStyle-CssClass="gridPager"
        AllowPaging="true"
        PageSize="15"
        onpageindexchanging="GridView1_PageIndexChanging"
        onrowcancelingedit="GridView1_RowCancelingEdit"
        onrowdeleting="GridView1_RowDeleting"
        onrowediting="GridView1_RowEditing"
        onrowupdating="GridView1_RowUpdating" onrowdatabound="GridView1_RowDataBound">
        <Columns>
        <asp:BoundField DataField="Employeename" HeaderText="Employee Name" />
        <asp:BoundField DataField="Salary" HeaderText="Salary" />
        <asp:TemplateField HeaderText="Department Name">
        <ItemTemplate>
        <asp:Literal ID="litDepartment" runat="server" Text='<%#Eval("Department_id") %>'></asp:Literal>
        </ItemTemplate>
        <EditItemTemplate>
        <asp:DropDownList ID="ddlDepartment" runat="server">
        </asp:DropDownList>
        </EditItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </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.Collections.Generic;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    private Employee employee = new Employee();
    private Department department = new Department();
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.CellSpacing = -1;
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        GridView1.DataSource = employee.ReadAll();
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void GridView1_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }
    protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        GridViewRow currentRow = GridView1.Rows[e.RowIndex];
        String dataKey = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        String employeeName = ((TextBox)currentRow.Cells[1].Controls[0]).Text;
        String salary = ((TextBox)currentRow.Cells[2].Controls[0]).Text;
        String department_id = ((DropDownList)currentRow.FindControl("ddlDepartment")).SelectedValue;
        try
        {
            employee = new Employee();
            employee.Id = Convert.ToInt16(dataKey);
            employee.Employeename = employeeName;
            employee.Salary = Convert.ToDecimal(salary);
            employee.Department_id = Convert.ToInt16(department_id);
            employee.UpdateById(employee);
        }
        catch { }

        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void GridView1_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void GridView1_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        String dataKey = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        employee.DeleteById(dataKey);
        GridView1.EditIndex = -1;
        BindGrid();
    }
    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        GridViewRow currentRow = e.Row;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton delete = (LinkButton)currentRow.Cells[0].Controls[2];
            if (delete.Text == "Delete")
            {
                delete.Attributes.Add("onclick", "DeleteConfirmation()");
            }
            try
            {

                Literal departmentName = (Literal)currentRow.Cells[3].FindControl("litDepartment");
                departmentName.Text = department.ReadAllById(departmentName.Text)[0].Departmentname;
            }
            catch
            {
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow &&
           (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            String Department_id = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

            DropDownList ddlDepartment = (DropDownList)currentRow.Cells[3].FindControl("ddlDepartment");
            ddlDepartment.DataSource = department.ReadAll();
            ddlDepartment.DataTextField = "Departmentname";
            ddlDepartment.DataValueField = "Id";
            ddlDepartment.DataBind();

            ddlDepartment.SelectedValue = Department_id;
        }
    }
}


********************************************************************************
/*  Connection Class*

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;
        }
    }
}


*******************************************************************************
/*Connection Class*/
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;
        }
    }
}

*******************************************************************************
/*Department  Class*/
#region Namespaces
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
#endregion

/// <summary>
/// class c
/// </summary>
 public class Department
 {
#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 _Departmentname;
     /// <summary>
     ///Gets or Sets the String value of Departmentname
     /// </summary>
      public String Departmentname { get { return _Departmentname;} set { _Departmentname = 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 Department()
      {
        ConnectionString=Connection.Cs;
      }

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

#region Public Methods

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


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

     /// <summary>
     /// This meathod returns all records of Department table by column Id.
     /// </summary>
     /// <param name="Id"></param>
     /// <returns>All rows of Department table.</returns>


      public List<Department> ReadAllById(String id)
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            List<Department> list = new List<Department>();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select * From [dbo].[Department] Where [Id]=@ID",con);
            cmd.Parameters.AddWithValue("@Id",id);
            using(table = cmd.ExecuteReader())
             {
              while (table.Read())
               {
                Department obj = new Department();
                obj._Id = table.GetInt32(0);
                obj._Departmentname = table.GetString(1);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

#endregion

 }

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

/*Employee Class*/

#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;} }

      private Int32 _Department_id;
     /// <summary>
     ///Gets or Sets the Int32 value of Department_id
     /// </summary>
      public Int32 Department_id { get { return _Department_id;} set { _Department_id = 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 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);
                obj._Department_id = table.GetInt32(3);
                list.Add(obj);
               }
               return list;
              }
             }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

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


      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,[Department_id] = @Department_id Where [Id] =@Id",con);
           cmd.Parameters.AddWithValue("@Employeename",obj._Employeename);
           cmd.Parameters.AddWithValue("@Salary",obj._Salary);
           cmd.Parameters.AddWithValue("@Department_id",obj._Department_id);
           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

#region Private Methods
     /// <summary>
     /// This meathod returns empty list.
     /// </summary>
      private List<Employee> GetEmptyList(List<Employee> obj)
       {
          obj.Add(new Employee());
          return obj;
       }
#endregion
 }

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

/*Web.config File*/

<connectionStrings>
<add name="cs" connectionString="Data Source=YOUR DATA SOURCE;Initial Catalog=softwarekaffee;Persist Security Info=True;User ID=sa;Password=YOUR PASSWORD"/>
</connectionStrings>

*******************************************************************************
/*Database Schema*/

Go
Create database softwarekaffee

Go
use softwarekaffee 

Go
create table Department
(
Id int identity primary key,
DepartmentName nvarchar(30)
)
Insert Into Department Values ('Sales');
Insert Into Department Values ('Production');
Insert Into Department Values ('Purchase');
Insert Into Department Values ('Stock');

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

Insert Into Employee Values ('Kaushik',41000,1);
Insert Into Employee Values ('Rahul',25000,2);
Insert Into Employee Values ('Sumit',26000,3);
Insert Into Employee Values ('Ravi',40000,4);
Insert Into Employee Values ('Rajeev',41000,1);
Insert Into Employee Values ('Amit',25000,2);
Insert Into Employee Values ('Gautam',26000,3);
Insert Into Employee Values ('Ranveer',40000,4);
Insert Into Employee Values ('Devendra',40000,4);
Insert Into Employee Values ('Sunil',40000,4);