Sunday, March 25, 2012

Awesome ListView in Asp.net C#



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

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

 body {}
.Table{width:500px;background:#ffffff;border:1px solid #000000; border-collapse:separate;}
.Table th{border:0px;background:url('Images/hfbg.jpg') repeat-x;color:#ffffff;text-align:center;font-size:18px;}

.Table tr,td{height:24px;}
.Table tfoot td{border:0px;background:url('Images/hfbg.jpg') repeat-x;color:#ffffff;text-align:center;font-size:18px;}
.Table td{padding-left:10px;border:1px solid #b5b5b5}

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

.TablePager{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 ListView control Asp.Net</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" >
        <LayoutTemplate>
        <table class="Table">
        <thead>
        <tr>
        <th>Employee Name</th>
        <th>Salary</th>
        </tr>
        </thead>
        <tbody>
            <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
        </tbody>
        <tfoot>
        <tr>
        <td colspan="2"></td>
        </tr>
        </tfoot>
        </table>
        </LayoutTemplate>
     
        <ItemTemplate>
        <tr>
        <td><%# Eval("Employeename")%></td>
        <td><%# Eval("Salary")%></td>
        </tr>
        </ItemTemplate>
     
        <AlternatingItemTemplate>
        <tr class="altRow">
        <td><%# Eval("Employeename")%></td>
        <td><%# Eval("Salary")%></td>
        </tr>
        </AlternatingItemTemplate>
     
        </asp:ListView>

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

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

using System;

public partial class _Default : System.Web.UI.Page
{
    private Employee employee = new Employee();

    private delegate void BindEmployee();

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

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

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

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

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

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



Monday, March 19, 2012

Entity data model tutorial


Open Visual Studio and create an ASP.NET Web Application project named BusinessObjects.
a. Click File, point to New, and click Project.



b. Select the Console Application template and change the project name to   EntityframeworkExample.


Right click on your solution navigate to Add further navigate to New item....


Choose Ado.Net Entity Data Model and name it SoftwareKaffee.edmx


The Entity Data Model Wizard shows up and you now can use this to query your database and generate the model diagram, as long as you supply it with the right credentials. In the Wizard, click "Generate from Database" and click Next.


Supply it with the right server name, authentication, credentials, and the database name


Select your tables


This is a graphical representation of the Entity Data Model (EDM) that's generated by the wizard.
 


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

using System;
using System.Linq;

namespace BusinessObjects
{
    class Program
    {
        static void Main(string[] args)
        {
            softwarekaffeeEntities databaseEntities = new softwarekaffeeEntities();
            var products = databaseEntities.Products.ToList();
            Console.WriteLine("Reading product details.");
            foreach (var data in products)
            {
                Console.WriteLine("Prosuct Id {0} | Product Name {1} | Quantity {2} | Unit Price {3}",
                    data.ProductId,
                    data.ProductName,
                    data.Quantity,
                    data.UnitPrice);
            }
            Console.Read();
        }
    }
}

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

Go
create database SoftwareKaffee

Go
use SoftwareKaffee

Go
Create table Products
(
    ProductId int identity primary key,
    ProductName varchar(50),
    ProductDetails nvarchar(200),
    UnitPrice decimal(7,2),
    Quantity int
)

Go
insert into Products values('Dell Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',55000,4)
insert into Products values( 'HCL Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',15000,30 )
insert into Products values( 'HP Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB', 23000 ,4 )
insert into Products values( 'HCL Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',35000,20 )
insert into Products values( 'Linovo Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 2GB',25000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',30000,30 )
insert into Products values( 'Dell Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',45000,10 )
insert into Products values( 'HP Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',55000,30 )
insert into Products values( 'HCL Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 2GB',35000,20 )
insert into Products values( 'Linovo Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',25000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',30000,60 )
insert into Products values( 'Dell Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',35000,30 )
insert into Products values( 'HP Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',55000,30 )
insert into Products values( 'HCL Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',34000,20 )
insert into Products values( 'Linovo Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',35000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',40000,30 )
insert into Products values( 'Dell Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',65000,30 )
insert into Products values( 'HP Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',75000,1 )
insert into Products values( 'HCL Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',45000,30 )
insert into Products values( 'Linovo Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',45000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',37000,5 )


AjaxToolKit Editor example in Asp.Net c#



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

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

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit.HTMLEditor" tagprefix="cc2" %>

<!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>AjaxToolKit Editor in Asp.Net c#</title>
    <style type="text/css">
       
    .htmleditor
    {
    width:500px;
    height:200px;
    }
    .htmleditor .ajax__htmleditor_editor_container
    {
    border: 1px solid #C2C2C2;
    }
    .htmleditor .ajax__htmleditor_editor_toptoolbar
    {
    background-color:#F0F0F0; padding: 0px 2px 2px 2px;
    }
    .htmleditor .ajax__htmleditor_editor_toptoolbar .ajax__htmleditor_toolbar_button
    {
    background-color:#C2C2C2; margin:2px 0px 0px 0px;
    }
    .htmleditor .ajax__htmleditor_editor_toptoolbar .ajax__htmleditor_toolbar_button_hover
    {
    background-color:#3C8AFF;
    }
    .htmleditor .ajax__htmleditor_editor_toptoolbar div.ajax__htmleditor_toolbar_button span.ajax__htmleditor_toolbar_selectlable
    {
    font-family:Arial; font-size:12px; font-weight:bold;
    }
    .htmleditor .ajax__htmleditor_editor_toptoolbar div.ajax__htmleditor_toolbar_button select.ajax__htmleditor_toolbar_selectbutton
    {
    font-size:12px; font-family:arial; cursor:pointer;
    }
    .htmleditor .ajax__htmleditor_editor_toptoolbar div.ajax__htmleditor_toolbar_button select.ajax__htmleditor_toolbar_selectbutton option
    {
    font-size:12px;
    }
    .htmleditor .ajax__htmleditor_editor_editpanel
    {
    border-width: 0px;
    border-top: 1px solid #C2C2C2;
    border-bottom: 1px solid #C2C2C2;
    }
    .htmleditor .ajax__htmleditor_editor_bottomtoolbar
    {
    background-color:#F0F0F0; padding: 0px 0px 2px 2px;
    }
    .htmleditor .ajax__htmleditor_editor_bottomtoolbar .ajax__htmleditor_toolbar_button
    {
    background-color:#C2C2C2; margin:0px 4px 0px 0px;
    }
    .htmleditor .ajax__htmleditor_editor_bottomtoolbar .ajax__htmleditor_toolbar_button_hover
    {
    background-color:#3C8AFF;
    }

    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    <h2>AjaxToolKit Editor example in Asp.Net c#</h2>
   
    <p>
     
        <cc2:Editor ID="Editor1" runat="server" CssClass="htmleditor"/>
    </p>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Get Text"
            onclick="Button1_Click" />
    </p>
    <p id="result" runat="server"></p>
    </div>
    </form>
</body>
</html>


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

using System;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        result.InnerHtml = Editor1.Content;
    }
}

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


Saturday, March 17, 2012

Uploading downloading pictures to from a SQL Serve in Asp.Net c#


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

<%@ 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>Uploading downloading pictures to from a SQL Serve in Asp.Net c#</title>
    <style type="text/css">
    .imgStyle
    {
    width:90px;
    height:100px;
    border:1px solid #d1d1e8;
    padding:2px;
    margin:2px;
    background-color:#d1d1e8;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Uploading downloading pictures to from a SQL Serve</h2>
    <p id="result" runat="server"></p>
    <p>Image tag:</p>
    <p><asp:TextBox ID="txtTag" runat="server"></asp:TextBox></p>
    <p>Browse image from your computer:</p>
    <p><asp:FileUpload ID="FileUpload1" runat="server" /></p>
    <p><asp:Button ID="butSave" runat="server" Text="Upload" onclick="butSave_Click" /></p>
    </div>
    <hr />
    <div>
        <asp:GridView ID="GridView1"
        runat="server"
        ShowHeader="false"
        AutoGenerateColumns="false">
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
        <asp:Image ID="Image1"
                   CssClass="imgStyle"
                   ToolTip='<%# Eval("Tag") %>'
                   runat="server"
                   ImageUrl='<%# "Handler.ashx/ReadImagegalleryForImgdataById?id=" + Eval("Id") %>'/>      
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>      
    </div>
    </form>
</body>
</html>

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

using System;

public partial class _Default : System.Web.UI.Page
{
    private Imagegallery imageGallery = new Imagegallery();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
         
        }
    }
    protected void butSave_Click(object sender, EventArgs e)
    {
        try
        {
            imageGallery = new Imagegallery();
            imageGallery.Tag = txtTag.Text;
            imageGallery.Imgdata = FileUpload1.FileBytes;
            imageGallery.Create(imageGallery);

        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
    }

    private void BindGrid()
    {
        imageGallery = new Imagegallery();
        GridView1.DataSource = imageGallery.ReadAll();
        GridView1.DataBind();
    }
}

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

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

/// <summary>
/// class Imagegallery
/// </summary>
 public class Imagegallery
 {
#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 _Tag;
      /// <summary>
      ///Gets or Sets the String value of Tag
      /// </summary>
      public String Tag { get { return _Tag;} set { _Tag = value;} }

      private Byte[] _Imgdata;
      /// <summary>
      ///Gets or Sets the Byte[] value of Imgdata
      /// </summary>
      public Byte[] Imgdata { get { return _Imgdata;} set { _Imgdata = 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 Imagegallery()
      {
        ConnectionString=Connection.Cs;
      }

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

#region Public Methods


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

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

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

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

      /// <summary>
      /// This meathod return rows of type image from Imagegallery table by column Id.
      /// </summary>
      /// <param name="Id"></param>
      /// <returns>Rows of type image from Imagegallery table.</returns>

      public System.IO.Stream ReadImagegalleryForImgdataById(String id)
       {
        try
         {
            con = new SqlConnection(ConnectionString);
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
          cmd = new SqlCommand("Select [Imgdata] From [dbo].[Imagegallery] Where [Id]=@Id",con);
          cmd.Parameters.AddWithValue("@Id",id);
          return new System.IO.MemoryStream((Byte[])cmd.ExecuteScalar());
         }
        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>

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

/*Handler.ashx code*/

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.IO;

public class Handler : IHttpHandler{
 
    public void ProcessRequest (HttpContext context) {
        String ID;
        if (context.Request.QueryString["id"] != null)
            ID = context.Request.QueryString["id"].ToString();
        else
            throw new ArgumentException("No parameter specified");
        context.Response.ContentType = "image/jpeg";
        Stream strm = new Imagegallery().ReadImagegalleryForImgdataById(ID);
        Byte[] buffer = new byte[2048];
        Int32 byteSeq = strm.Read(buffer, 0, 2048);
        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

**************************************************************************
Go
Create database softwarekaffee

Go
use softwarekaffee 

Go
create table ImageGallery
(
Id int identity primary key,
Tag nvarchar(30),
ImgData image
)

Thursday, March 15, 2012

ModalPopup Extender example in Asp.Net c#




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

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

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<!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>ModalPopup Extender example in Asp.Net c#</title>
    <style type="text/css">
    .modalBackground
    {
        background-color: Black;
        filter: alpha(opacity=70);
        opacity: 0.7;
        z-index: 0;
    }
    .PnlPopUp
    {
        width:500px;
        height:700px;
        background:#ffffff;
        margin:5px;
        border:2px solid #cacac2;
        padding:2px;
        z-index: 1;
    }
 
    .CloseDialog
    {
        float:left;
        margin-left:3px;
        background: url(./red.png) no-repeat top;
        z-index: 1;
        cursor:pointer;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    <h2> ModalPopup Extender example</h2>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Popup" />
        <cc1:ModalPopupExtender
            ID="Button1_ModalPopupExtender"
            runat="server"
            BackgroundCssClass="modalBackground"
            Enabled="True"
            TargetControlID="Button1"
            PopupControlID="pnlPopUp">
        </cc1:ModalPopupExtender>
    </p>

    <asp:Panel runat="Server" ID="pnlPopUp" CssClass="PnlPopUp" Style="display:none;">
    <asp:ImageButton
    ID="ClosePopUp"
    ImageUrl="~/red.png"
    runat="server"
    CssClass="CloseDialog"
    style="float:right"/>
 
    </asp:Panel>
 
    </div>
    </form>
</body>
</html>

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

using System;

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

    }
}
************************************************************************

TextBoxWatermark Extender example in Asp.Net c#



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

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

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<!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>TextBoxWatermark Extender example in Asp.Net c#</title>
    <style type="text/css">
    .watermark
    {
        color:#999999;
        font-style:italic;
    }
    .watermark:focus
    {
    border: solid 1px #fffa93;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    <h2> TextBoxWatermark Extender example</h2>
    <p>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <cc1:TextBoxWatermarkExtender
        ID="TextBox1_TextBoxWatermarkExtender"
        runat="server"
        Enabled="True"
        TargetControlID="TextBox1"
        WatermarkCssClass="watermark"
        WatermarkText="Enter your name here">
        </cc1:TextBoxWatermarkExtender>
    </p>
    <p>
        &nbsp;</p>
    </div>
    </form>
</body>
</html>


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

using System;

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

    }
}

Calendar Extender example in Asp.Net c#



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

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

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<!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>Calendar Extender example in Asp.Net c#</title>
    <style type="text/css">

    .cal_Theme1 .ajax__calendar_container
    {
    margin:0px 3px 0px 3px;
        background-color: #fff;
        border:solid 1px #e3e3e3;
    }

    .cal_Theme1 .ajax__calendar_header  {
        background-color: #fff;
        margin-bottom: 4px;
    }

    .cal_Theme1 .ajax__calendar_title,
    .cal_Theme1 .ajax__calendar_next,
    .cal_Theme1 .ajax__calendar_prev    {
        color:#000;
        padding-top: 3px;
    }

    .cal_Theme1 .ajax__calendar_body    {
        background-color: #fff;
        border: solid 1px #cccccc;
    }

    .cal_Theme1 .ajax__calendar_dayname {
        text-align:center;
        font-weight:bold;
        margin-bottom: 4px;
        margin-top: 2px;
    }

    .cal_Theme1 .ajax__calendar_day
    {
    color: #000;
        text-align:center;
    }

    .cal_Theme1 .ajax__calendar_hover .ajax__calendar_day,
    .cal_Theme1 .ajax__calendar_hover .ajax__calendar_month,
    .cal_Theme1 .ajax__calendar_hover .ajax__calendar_year,
    .cal_Theme1 .ajax__calendar_active  {
        color: #c50c28;
        font-weight: bold;
        background-color: #ffffff;
    }

    .cal_Theme1 .ajax__calendar_today
    {
        font-weight:bold;
    }

    .cal_Theme1 .ajax__calendar_other,
    .cal_Theme1 .ajax__calendar_hover .ajax__calendar_today,
    .cal_Theme1 .ajax__calendar_hover .ajax__calendar_title {
        color: #000;
    }

</style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    <h2> Calendar Extender example</h2>
    <p>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <cc1:CalendarExtender
        ID="TextBox1_CalendarExtender"
        CssClass="cal_Theme1"
        PopupButtonID="Image1"
        PopupPosition="Right"
        runat="server"
        Enabled="True"
        TargetControlID="TextBox1">
        </cc1:CalendarExtender>
        <asp:Image ID="Image1" runat="server" ImageUrl="~/Calendar.png" Width="16px" />
    </p>
    <p>
        &nbsp;</p>
    </div>
    </form>
</body>
</html>


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

using System;

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

    }
}


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

ConfirmButton Extender example in Asp.Net c#



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

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

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>

<!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>ConfirmButton Extender example in Asp.Net c#</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
    <h2> ConfirmButton Extender example</h2>
    <p>
        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    </p>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Click Me"
            onclick="Button1_Click"/>
        <cc1:ConfirmButtonExtender
        ID="Button1_ConfirmButtonExtender"
        runat="server"
        ConfirmText="Are you sure?&#10;You want to run the server code."
        OnClientCancel="onCancel"
        ConfirmOnFormSubmit="false"
        Enabled="True"
        TargetControlID="Button1">
        </cc1:ConfirmButtonExtender>
    </p>
    </div>
    </form>
</body>
</html>
<script language="javascript" type="text/javascript">
    function onCancel()
    {
        var lblMsg = $get('<%=lblMessage.ClientID%>');
        lblMsg.innerHTML = "You clicked the <b>Cancel</b> button of AJAX confirm.";
    }
</script>


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

using System;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "You clicked the <b>OK</b> button of AJAX confirm";
    }
}

How to add new Ajax control toolkit in vs 2008 or 2010


To install the Ajax Control Toolkit,
first download the zip file from www.asp.net/ajaxlibrary/download.ashx.
Unzip the files into any directory.
Open your Visual Web Developer and right click in the Toolbox area. Select "Add Tab."  





Name the tab with something like "AjaxTooKit."



Right click the new tab area, and select "Choose Items..." 



This will bring up a dialog box to "Choose Toolbox Items." Select the "Browse" button. 


Find and select to open the "AjaxControlToolkit.dll" file. 



The Choose Toolbox Items dialog will appear, this time with the Ajax Tookit controls selected. Select the "OK" button.



Open or create a web form within your project. Now when you open your toolbox, you will see all of the Ajax Control Toolkit controls, ready for use within your applications.




Wednesday, March 14, 2012

Insert,Read,Update,Delete in GridView in Asp.Net


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

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

 body {border:1px solid #000;padding:40px;}
.gridView{width:400px;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;}

.heading{font:15px;font-weight:bold;width:300px;border-bottom:1px solid #000;}

a{color:#000;text-decoration:none}
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>Insert,Read,Update,Delete in GridView in Asp.Net</title>
    <link href="Resources/StyleSheet/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p id="result" runat="server"></p>
        <%="You are viewing page "+(GridView1.PageIndex+1)+" of "+GridView1.PageCount+" ,row count "+GridView1.Rows.Count %>
        <asp:GridView ID="GridView1"
        runat="server"
        AutoGenerateColumns="false"
        ShowFooter="true"
        DataKeyNames="Id"
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        CssClass="gridView"
        AlternatingRowStyle-CssClass="altRow"
        PagerStyle-CssClass="gridPager"
        onrowcancelingedit="GridView1_RowCancelingEdit"
        onrowdeleting="GridView1_RowDeleting"
        onrowediting="GridView1_RowEditing"
        onrowupdating="GridView1_RowUpdating">
        <Columns>
        <asp:TemplateField HeaderText="Department Name">
     
        <ItemTemplate>
            <asp:Literal ID="Literal1" runat="server" Text='<%# Eval("departmentname") %>'></asp:Literal>
        </ItemTemplate>
     
        <EditItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("departmentname") %>'></asp:TextBox>
        </EditItemTemplate>
     
        <FooterTemplate>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
        </FooterTemplate>
     
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

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

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

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

    private void BindGrid()
    {
        GridView1.DataSource = department.ReadAll();
        GridView1.DataBind();
    }

    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)
    {
        try
        {
            GridViewRow currentRow = GridView1.Rows[e.RowIndex];
            String dataKey = GridView1.DataKeys[e.RowIndex].Values[0].ToString();

            String departmentName = ((TextBox)currentRow.FindControl("TextBox1")).Text;
            department = new Department();
            department.Id = int.Parse(dataKey);
            department.Departmentname = departmentName;
            department.UpdateById(department);
            GridView1.EditIndex = -1;
            BindGrid();
            result.InnerHtml = "Record updated.";
        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
    }

    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)
    {
        try
        {
        String dataKey = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        department = new Department();
        department.DeleteById(dataKey);
        GridView1.EditIndex = -1;
        BindGrid();
        result.InnerHtml = "Record deleted.";
        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            String departmentName = ((TextBox)GridView1.FooterRow.FindControl("TextBox2")).Text;
            department = new Department();
            department.Departmentname = departmentName;
            department.Create(department);
            result.InnerHtml = "Record inserted.";
            BindGrid();
        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
    }
}

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

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 is for inserting record in Department table.
      /// </summary>
      /// <param name="object of Department"></param>
      /// <returns>Number of row affected by query.</returns>

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


     /// <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 is for updating record in Department table by column Id.
      /// </summary>
      /// <param name="object of Department"></param>
      /// <returns>Number of row affected by query.</returns>

      public Int32 UpdateById(Department obj)
      {
          using (con = new SqlConnection(ConnectionString))
          {
              try
              {
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }
                  cmd = new SqlCommand("Update [dbo].[Department] Set [Departmentname] = @Departmentname Where [Id] =@Id", con);
                  cmd.Parameters.AddWithValue("@Departmentname", obj._Departmentname);
                  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 Department 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].[Department] 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');

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


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


DataContext.ExecuteCommand Method and DataContext.ExecuteQuery Method in Linq



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

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

 body {border:1px solid #000;padding:40px;}
.gridView{width:400px;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;}

.heading{font:15px;font-weight:bold;width:300px;border-bottom:1px solid #000;}

a{color:#000;text-decoration:none}
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>DataContext.ExecuteCommand Method and DataContext.ExecuteQuery Method in Linq</title>
    <link href="Resources/StyleSheet/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <p id="result" runat="server"></p>
    <p class="heading">Create Department</p>
    <p>Department Name</p>
    <p><asp:TextBox ID="txtDepartment" runat="server"></asp:TextBox></p>
    <p><asp:Button ID="butSaveDept" runat="server" Text="Save"
            onclick="butSaveDept_Click" /></p>
 
    <p class="heading">Read Department</p>
    <asp:GridView ID="GridDept" runat="server"
    AutoGenerateColumns="false"
    DataKeyNames="id"
    AutoGenerateEditButton="true"
    AutoGenerateDeleteButton="true"
    CssClass="gridView"
    AlternatingRowStyle-CssClass="altRow"
    onrowcancelingedit="GridDept_RowCancelingEdit"
    onrowdeleting="GridDept_RowDeleting"
    onrowediting="GridDept_RowEditing"
    onrowupdating="GridDept_RowUpdating">
    <Columns>
    <asp:BoundField DataField="departmentname" HeaderText="Department Name" />
    </Columns>
    </asp:GridView>
 
    </div>
    </form>
</body>
</html>

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

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

public partial class _Default : System.Web.UI.Page
{
    private DataClassesDataContext ctx = new DataClassesDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDepartment();
        }
    }

    private void BindDepartment()
    {
        ctx = new DataClassesDataContext();
        GridDept.DataSource = ctx.ExecuteQuery<Department>("Select *from department");
        GridDept.DataBind();
    }

    protected void butSaveDept_Click(object sender, EventArgs e)
    {
        try
        {
            ctx = new DataClassesDataContext();
            ctx.ExecuteCommand("Insert into department values({0})", txtDepartment.Text);
            ctx.SubmitChanges();
            result.InnerHtml = "Row inserted.";
        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
        finally {
            BindDepartment();
        }
    }
    protected void GridDept_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        GridDept.EditIndex = e.NewEditIndex;
        BindDepartment();
    }
    protected void GridDept_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        GridDept.EditIndex = -1;
        BindDepartment();
    }
    protected void GridDept_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        try
        {
            GridViewRow currentRow = GridDept.Rows[e.RowIndex];
            String dataKey = GridDept.DataKeys[currentRow.RowIndex].Values[0].ToString();

            ctx = new DataClassesDataContext();
            ctx.ExecuteCommand("Delete from department where id={0}", dataKey);
            result.InnerHtml = "Row deleted.";
            GridDept.EditIndex = -1;
        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
        finally
        {
            BindDepartment();
        }
    }
    protected void GridDept_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        try
        {
            GridViewRow currentRow = GridDept.Rows[e.RowIndex];
            String dataKey = GridDept.DataKeys[currentRow.RowIndex].Values[0].ToString();
            String departmentName = ((TextBox)currentRow.Cells[1].Controls[0]).Text;

            ctx = new DataClassesDataContext();
            ctx.ExecuteCommand("Update department set departmentname={0} where id={1}",  departmentName,dataKey);
            result.InnerHtml = "Row updated.";
            GridDept.EditIndex = -1;
        }
        catch (Exception ex)
        {
            result.InnerHtml = ex.Message;
        }
        finally
        {
            BindDepartment();
        }
    }
}

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

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

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