Search...

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

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


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


No comments: