Вы находитесь на странице: 1из 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 Asp.net Gridview CRUD Database Preparation

Asp.net Gridview CRUD

Database Preparation

Create Database db27122017 GO Use db27122017 GO Create table Employee

(

ID int identity(1,1) Primary Key, FirstName varchar(20) not null, LastName varchar(20) not null, Salary int

)

GO Create procedure spGetEmployees as

begin

Select * from Employee

end GO Insert into Employee values('Salman', 'Khan', 10000), ('Kat','Kaif', 20000) GO execute spGetEmployees go Create procedure spInsEmployees

(

 

@Firstname varchar(20), @Lastname varchar(20), @Salary int

)

as

begin

 

Insert into Employee values(@Firstname, @Lastname, @Salary)

end

GO Create procedure spUpdEmployees

(

@ID int, @Firstname varchar(20), @Lastname varchar(20),

Page 1 of 11

GO Create procedure spUpdEmployees ( @ID int , @Firstname varchar ( 20 ), @Lastname varchar (
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 @Salary int ) as begin

@Salary int

)

as

begin

Update Employee Set Firstname = @Firstname, LastName = @Lastname, Salary = @Salary Where ID = @ID

end

GO

Create procedure spDelEmployees

(

)

as

begin

@ID int

Delete from Employee Where ID = @ID

end

GO

Create an Asp.net Web Forms project

Add an Employee class in the Models folder

Employee.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web;

namespace GridViewCRUDJquery.Models

{

public class Employee

{

public int ID { get; set; } public String FirstName { get; set; } public String LastName { get; set; }

Page 2 of 11

{ get ; set ; } public String FirstName { get ; set ; } public
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 public int Salary { get

public int Salary { get; set; }

}

}

Add a DataAccess static class for the ADO.NET CRUD methods

DataAccess.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Configuration;

namespace GridViewCRUDJquery.Models

{

public class EmployeeDataAccess

{

private static string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

/// <summary> /// Get list of Employees /// </summary>

public static List<Employee> GetEmployees()

{

var Employees = new List<Employee>(); var con = new SqlConnection(conString); try

{

con.Open(); SqlCommand cmd = new SqlCommand("spGetEmployees", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read())

{

Employee employee = new Employee(); employee.ID = Convert.ToInt32(dr["ID"]); employee.FirstName = dr["FirstName"].ToString(); employee.LastName = dr["LastName"].ToString();

Page 3 of 11

= dr[ "FirstName" ].ToString(); employee.LastName = dr[ "LastName" ].ToString(); Page 3 of 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 employee.Salary = Int32 .Parse(dr[ "Salary"

employee.Salary = Int32.Parse(dr["Salary"].ToString()); Employees.Add(employee);

}

return Employees;

}

catch (Exception ex)

{

//log ex

return null;

}

finally

{

con.Close();

}

}

/// <summary> /// Add Employee

/// </summary> public static Boolean AddEmployee(Employee Employee)

{

 

var con = new SqlConnection(conString); try

{

con.Open();

SqlCommand cmd = new SqlCommand("spInsEmployees", con)

{

CommandType = CommandType.StoredProcedure

}; cmd.Parameters.AddWithValue("@FirstName", Employee.FirstName); cmd.Parameters.AddWithValue("@LastName", Employee.LastName); cmd.Parameters.AddWithValue("@Salary", Employee.Salary); if (cmd.ExecuteNonQuery() > 0)

{

return true; // success

}

else

{

return false; //fail

}

}

catch (Exception ex)

{

//log error message ex return false; // return error message

}

finally

{

con.Close();

}

}

/// <summary> /// Update Employee

Page 4 of 11

message } finally { con.Close(); } } /// <summary> /// Update Employee Page 4 of 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 /// </summary> public static Boolean

/// </summary>

public static Boolean UpdateEmployee(Employee Employee)

{

 

SqlConnection con = new SqlConnection(conString); try

{

con.Open(); var cmd = new SqlCommand("spUpdEmployees", con)

{

CommandType = CommandType.StoredProcedure

}; cmd.Parameters.AddWithValue("@ID", Employee.ID);

cmd.Parameters.AddWithValue("@FirstName", Employee.FirstName); cmd.Parameters.AddWithValue("@LastName", Employee.LastName); cmd.Parameters.AddWithValue("@Salary", Employee.Salary); if (cmd.ExecuteNonQuery() > 0)

{

return true; // success

}

else

{

return false; //fail

}

}

catch (Exception ex)

{

//log error message ex return false; // return error message

}

finally

{

con.Close();

}

}

/// <summary> /// Delete Employee /// </summary>

public static Boolean DeleteEmployee(int EmployeeId)

{

var con = new SqlConnection(conString); try

{

con.Open();

SqlCommand cmd = new SqlCommand("spDelEmployees", con)

{

CommandType = CommandType.StoredProcedure

}; cmd.Parameters.AddWithValue("@ID", EmployeeId); if (cmd.ExecuteNonQuery() > 0)

{

return true; // success

}

else

Page 5 of 11

"@ID" , EmployeeId); if (cmd.ExecuteNonQuery() > 0) { return true ; // success } else Page
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 { return false ; //fail

{

return false; //fail

}

}

catch (Exception ex)

{

//log error message ex return false; // return error message

}

}

}

finally

{

con.Close();

}

}

Add constr connection string in Web.config

<connectionStrings> <add name="DefaultConnection" connectionString="Data

Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-GridViewCRUDJquery-

20171223123156.mdf;Initial Catalog=aspnet-GridViewCRUDJquery-20171223123156;Integrated Security=True"

providerName="System.Data.SqlClient" />

<add name="constr" connectionString="Data Source=(localdb)\ProjectsV12;Initial Catalog=db27122017;Integrated Security=True;Connect

Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailo

ver=False" providerName="System.Data.SqlClient" />

</connectionStrings>

Page 6 of 11

ver=False" providerName="System.Data.SqlClient" /> </ connectionStrings > Page 6 of 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 Default.aspx <% @ Page Title

Default.aspx

<%
<%

@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"

CodeBehind="Default.aspx.cs" Inherits="GridViewCRUDJquery Default"

%>
%>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<asp:GridView ID="gvEmployees" runat="server" AllowPaging="true" ShowFooter="true" PageSize="5" AutoGenerateColumns="false" OnPageIndexChanging="gvEmployees_PageIndexChanging" OnRowCancelingEdit="OnRowCancelingEdit" OnRowCommand="OnRowCommand" OnRowDeleting="OnRowDeleting" OnRowEditing="OnRowEditing" OnRowUpdating="OnRowUpdating" HeaderStyle-BackColor="Gray" HeaderStyle-ForeColor="White" BackColor="SkyBlue">

<AlternatingRowStyle BackColor="#FFFFCC" />

<Columns> <asp:TemplateField HeaderText="ID"> <ItemTemplate> <asp:Label ID="lblID" runat="server" Text='

<%
<%

#Eval("ID")

%>
%>

'></asp:Label>

</ItemTemplate> <FooterTemplate> <asp:Label ID="lblAdd" runat="server"></asp:Label> </FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="First Name" HeaderStyle-Width="100px"> <ItemTemplate>

<asp:Label ID="lblFirstname" runat="server" Text='

<%
<%

#Eval("FirstName")

%>
%>

'></asp:Label>

 

</ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtFirstname" runat="server" Text='

<%
<%

#Eval("Firstname")

%>
%>

'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAddFirstname" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="100px"> <ItemTemplate>

%>
%>

'></asp:Label>

<asp:Label ID="lblLastname" runat="server" Text='

<%
<%

#Eval("LastName")

 

</ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtLastname" runat="server" Text='

<%
<%

#Eval("Lastname")

%>
%>

'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAddLastname" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField>

Page 7 of 11

asp : TextBox > </ FooterTemplate > </ asp : TemplateField > Page 7 of 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 < asp : TemplateField HeaderText

<asp:TemplateField HeaderText="Salary" HeaderStyle-Width="100px"> <ItemTemplate>

%>
%>
<asp:Label ID="lblSalary" runat="server" Text=' <% #Eval("Salary") %>
<asp:Label ID="lblSalary" runat="server" Text='
<%
#Eval("Salary")
%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtSalary" runat="server" Text='
<%
#Eval("Salary")

'></asp:Label>

'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAddSalary" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="100px"> <ItemTemplate> <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />

<span onclick="return confirm('Are you sure you want to delete this record?')"> <asp:LinkButton ID="btnDelete" Text="Delete" runat="server"

CommandName="Delete" /> </span> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" /> <br /> <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" /> </EditItemTemplate> <FooterTemplate> <asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView>

</asp:Content>

Page 8 of 11

asp : TemplateField > </ Columns > </ asp : GridView > </ asp : Content
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 Default.aspx.cs using System; using

Default.aspx.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web.Services; using GridViewCRUDJquery.Models;

namespace GridViewCRUDJquery

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindGrid();

}

}

public void BindGrid()

{

gvEmployees.DataSource = EmployeeDataAccess.GetEmployees(); gvEmployees.DataBind();

}

protected void OnRowEditing(object sender, GridViewEditEventArgs e)

{

gvEmployees.EditIndex = e.NewEditIndex; this.BindGrid();

}

protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)

{

Employee employee = new Employee(); employee.ID = int.Parse(((Label)gvEmployees.Rows[e.RowIndex].FindControl("lblID")).Text); employee.FirstName = ((TextBox)gvEmployees.Rows[e.RowIndex].FindControl("txtFirstName")).Text; employee.LastName = ((TextBox)gvEmployees.Rows[e.RowIndex].FindControl("txtLastName")).Text; employee.Salary = int.Parse(((TextBox)gvEmployees.Rows[e.RowIndex].FindControl("txtSalary")).Text);

EmployeeDataAccess.UpdateEmployee(employee); gvEmployees.EditIndex = -1;

BindGrid();

}

Page 9 of 11

)).Text); EmployeeDataAccess .UpdateEmployee(employee); gvEmployees.EditIndex = -1; BindGrid(); } Page 9 of 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 protected void OnRowDeleting( object sender,

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)

{

int ID = int.Parse(((Label)gvEmployees.Rows[e.RowIndex].FindControl("lblID")).Text); EmployeeDataAccess.DeleteEmployee(ID); gvEmployees.EditIndex = -1; BindGrid();

}

protected void gvEmployees_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

gvEmployees.PageIndex = e.NewPageIndex; BindGrid();

}

protected void OnUpdate(object sender, EventArgs e)

{

 

Employee employee = new Employee(); GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow; employee.ID = int.Parse((row.Cells[0].Controls[0] as TextBox).Text); employee.FirstName = (row.Cells[1].Controls[0] as TextBox).Text; employee.LastName = (row.Cells[2].Controls[0] as TextBox).Text; employee.Salary = int.Parse((row.Cells[3].Controls[0] as TextBox).Text);

EmployeeDataAccess.UpdateEmployee(employee); gvEmployees.EditIndex = -1; this.BindGrid();

}

protected void OnCancel(object sender, EventArgs e)

{

gvEmployees.EditIndex = -1; this.BindGrid();

}

protected void OnRowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName.Equals("Add"))

{

Employee employee = new Employee();

employee.FirstName = ((TextBox)gvEmployees.FooterRow.FindControl("txtAddFirstName")).Text; employee.LastName = ((TextBox)gvEmployees.FooterRow.FindControl("txtAddLastName")).Text; employee.Salary = int.Parse(((TextBox)gvEmployees.FooterRow.FindControl("txtAddSalary")).Text);

EmployeeDataAccess.AddEmployee(employee);

gvEmployees.EditIndex = -1; BindGrid();

}

}

Page 10 of 11

)).Text); EmployeeDataAccess .AddEmployee(employee); gvEmployees.EditIndex = -1; BindGrid(); } } Page 10 of 11
Project - Dot Net - Chapter 4 – Asp.net Gridview CRUD Author - Milind Sir

Project - Dot Net - Chapter 4 Asp.net Gridview CRUD

Author - Milind Sir

Date 27 th November 2017

Author - Milind Sir Date – 27 t h November 2017 protected void OnRowCancelingEdit( object sender,

protected void OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

gvEmployees.EditIndex = -1; BindGrid();

}

}

}

e) { gvEmployees.EditIndex = -1; BindGrid(); } } } Try out the Edit, Delete, Add buttons.

Try out the Edit, Delete, Add buttons.

Page 11 of 11

e) { gvEmployees.EditIndex = -1; BindGrid(); } } } Try out the Edit, Delete, Add buttons.