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

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



Post a Comment