A Simple Demonstration with ASP.net GridView

GridView is a powerful control of ASP.net. Here I tried to demonstrate gridview with a simple project. I have stored employee information then displayed it in gridview and insert, update and delete employee information.
Step 1: Create a table name hrm_employee and insert some sample data in it.

--Create Table : hrm_employee---
CREATE TABLE hrm_employee
(
emp_gid INT PRIMARY KEY IDENTITY,
emp_fullnm VARCHAR(100),
emp_nicknm VARCHAR(50),
emp_designation VARCHAR(100)
)

---Insert data ito table: hrm_employee----

-- Insert data i.e. row-1 ---
INSERT INTO hrm_employee
(
emp_fullnm
, emp_nicknm
, emp_designation
)
VALUES
(
'Md. Mahedee Hasan'
, 'Mahedee'
, 'Senior Software Engineer'
)

-- Insert data i.e. row-2 ---
INSERT INTO hrm_employee
(
emp_fullnm
, emp_nicknm
, emp_designation
)
VALUES
(
'Md. Asrafuzzaman'
, 'Emon'
, 'Senior Software Engineer'
)

-- Insert data i.e. row-3 ---
INSERT INTO hrm_employee
(
emp_fullnm
, emp_nicknm
, emp_designation
)
VALUES
(
'Md. Khondakar Enamul Haque'
, 'Rony'
, 'Broadcast Engineer'
)

Step 2: Create an ASP.net website with 3 Layers – DAL for data access layer, BLL for Business Logic Layer and presentation Layer. Also create another layer name Model for mapping with data.

Step 3: Create connection string in web.config file.





Step 4: Create Images Folder and store icon edit_icon.gif for edit and icon_remove.png for delete.
Step 5: Create EmployeeInfo model class.

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

///
/// Model class of EmployeeInfo
///

public class EmployeeInfo
{
public int EmpGid { get; set; }
public string EmpFullNm { get; set; }
public string EmpNickNm { get; set; }
public string EmpDesignation { get; set; }
}


Step 6: Create a DBConnector Class for connecting with database in DAL.

/// Class : DBConnector
/// Author : Md. Mahedee Hasan
/// Purpose : For Connecting with database
///Creation Date : 21/04/201
/// ==================================================================================================
/// || Modification History ||
/// -------------------------------------------------------------------------------------------------
/// Sl No. Date: Author: Ver: Area of Change:
///
///**************************************************************************************************

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public class DBConnector
{
private string connectionString = null;
private SqlConnection sqlConn = null;
private SqlCommand cmd = null;

public DBConnector()
{
connectionString = ConfigurationManager.ConnectionStrings["SQLServerConnectionString"].ToString();
}

public SqlCommand GetCommand()
{
cmd = new SqlCommand();
cmd.Connection = sqlConn;
return cmd;
}

public SqlConnection GetConn()
{
sqlConn = new SqlConnection(connectionString);
return sqlConn;
}

}


Step 7: Create EmployeeInfoDAL class in DAL layer for accessing data (Employee Information related) from database.

/// Class : EmployeeInfoDAL
/// Author : Md. Mahedee Hasan
/// Purpose : Retreving data from database
/// Creation Date : 21/04/2012
/// ==================================================================================
/// || Modification History ||
/// -----------------------------------------------------------------------------
/// Sl No. Date: Author: Ver: Area of Change:
///
/// ***************************************************************************

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

///
/// Summary description for EmployeeInfoDAL
///

public class EmployeeInfoDAL
{

private SqlConnection sqlConn;
private SqlCommand cmd;
private readonly DBConnector objDBConnector;

///
/// Constructor
///

public EmployeeInfoDAL()
{
objDBConnector = new DBConnector();
sqlConn = objDBConnector.GetConn();
cmd = objDBConnector.GetCommand();
}

///
/// Get all employee information
///
///

public DataTable GetEmployeeInfoAll()
{
DataTable tblEmpInfo = new DataTable();
SqlDataReader rdr = null;

cmd.CommandType = CommandType.Text;

cmd.CommandText = "SELECT emp_gid, emp_fullnm, emp_nicknm, emp_designation FROM hrm_employee";

try
{
if (sqlConn.State == ConnectionState.Closed)
sqlConn.Open();

rdr = cmd.ExecuteReader();
tblEmpInfo.Load(rdr);
}
catch (Exception exp)
{
throw (exp);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
sqlConn.Close();
}

return tblEmpInfo;

}

///
/// Insert Employee information
///
///
///

public string InsertEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
string msg = String.Empty;

int noOfRowEffected = 0;

try
{
if (sqlConn.State == ConnectionState.Closed)
sqlConn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO hrm_employee(emp_fullnm , emp_nicknm , emp_designation)"
+ " VALUES('" + objEmployeeInfo.EmpFullNm + "','" + objEmployeeInfo.EmpNickNm + "','" + objEmployeeInfo.EmpDesignation + "')";

noOfRowEffected = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception exp)
{
throw (exp);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
sqlConn.Close();
}

if (noOfRowEffected > 0)
return "Employee information saved successfully!";
else
return msg;
}

///
/// Update employee information
///
///
///

public string UpdateEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
string msg = String.Empty;

int noOfRowEffected = 0;

try
{
if (sqlConn.State == ConnectionState.Closed)
sqlConn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE hrm_employee SET emp_fullnm = '" + objEmployeeInfo.EmpFullNm +
"',emp_nicknm = '" + objEmployeeInfo.EmpNickNm + "', emp_designation = '" + objEmployeeInfo.EmpDesignation
+ "' WHERE emp_gid = " + objEmployeeInfo.EmpGid;

noOfRowEffected = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception exp)
{
throw (exp);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
sqlConn.Close();
}

if (noOfRowEffected > 0)
return "Employee information updated successfully!";
else
return msg;
}

///
/// Delete employee information
///
///
///

public string DeleteEmployeeInfo(int empGid)
{
string msg = String.Empty;

int noOfRowEffected = 0;

try
{
if (sqlConn.State == ConnectionState.Closed)
sqlConn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM hrm_employee"
+ " WHERE emp_gid = " + empGid;

noOfRowEffected = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception exp)
{
throw (exp);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
sqlConn.Close();
}

if (noOfRowEffected > 0)
return "Employee information deleted successfully!";
else
return msg;
}
}

Step 8: Create EmployeeInfoBLL in BLL for writing business logic and accessing data by DAL.

/// Class : EmployeeInfoBLL
/// Author : Md. Mahedee Hasan
/// Purpose : Business Logic Layer - Write business logic here
/// Creation Date : 21/04/2012
/// ==================================================================================================
/// || Modification History ||
/// -------------------------------------------------------------------------------------------------
/// Sl No. Date: Author: Ver: Area of Change:
///
/// **************************************************************************************************

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

///
/// Summary description for EmployeeInfoBLL
///

public class EmployeeInfoBLL
{
public EmployeeInfoBLL()
{

}

public DataTable GetEmployeeInfoAll()
{
try
{
EmployeeInfoDAL objEmployeeInfoDAL = new EmployeeInfoDAL();
return objEmployeeInfoDAL.GetEmployeeInfoAll();
}
catch (Exception exp)
{
throw (exp);
}
}

public string SaveEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
try
{
EmployeeInfoDAL objEmployeeInfoDAL = new EmployeeInfoDAL();
return objEmployeeInfoDAL.InsertEmployeeInfo(objEmployeeInfo);
}
catch (Exception exp)
{
throw (exp);
}
}

public string EditEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
try
{
EmployeeInfoDAL objEmployeeInfoDAL = new EmployeeInfoDAL();
return objEmployeeInfoDAL.UpdateEmployeeInfo(objEmployeeInfo);
}
catch (Exception exp)
{
throw (exp);
}
}

public string RemoveEmployeeInfo(int empGid)
{
try
{
EmployeeInfoDAL objEmployeeInfoDAL = new EmployeeInfoDAL();
return objEmployeeInfoDAL.DeleteEmployeeInfo(empGid);
}
catch (Exception exp)
{
throw (exp);
}
}
}


Step 9: Create a gridview and update form in UI page (Here Default.aspx).

Default.aspx

Full Name :
Nick Name :
Designation :


' /> ' OnClick="btnEdit_Click"> ' OnClick="btnDelete_Click">


Defult.aspx.cs

/// Author : Md. Mahedee Hasan
/// Purpose : Code behind of Default.aspx page
/// Creation Date : 21/04/2012
/// ==================================================================================================
/// || Modification History ||
/// -------------------------------------------------------------------------------------------------
/// Sl No. Date: Author: Ver: Area of Change:
///
/// **************************************************************************************************

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

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

protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{
Load_gvEmpInfo();
}
}

///
/// Binding gridview gvEmpInfo
///

private void Load_gvEmpInfo()
{
EmployeeInfoBLL objEmployeeInfoBLL = new EmployeeInfoBLL();
this.gvEmpInfo.DataSource = objEmployeeInfoBLL.GetEmployeeInfoAll();
this.gvEmpInfo.DataBind();
}

protected void btnEdit_Click(object sender, EventArgs e)
{

this.btnSave.Text = "Edit";

LinkButton btnEdit = sender as LinkButton;

//Identify the clicked row
int rowIndex = Convert.ToInt32(btnEdit.Attributes["RowIndex"]);

GridViewRow gvRow = this.gvEmpInfo.Rows[rowIndex];

//Identify the hidden filed value of clicked row
int emp_gid = Convert.ToInt32(((HiddenField)gvRow.FindControl("hidemp_gid")).Value);

this.txtEmpFullNm.Text = gvRow.Cells[0].Text;
this.txtEmpNickNm.Text = gvRow.Cells[1].Text;
this.txtDesignation.Text = gvRow.Cells[2].Text;

this.hf_emp_gid.Value = emp_gid.ToString();

}

protected void btnDelete_Click(object sender, EventArgs e)
{
LinkButton btnDelete = sender as LinkButton;

//Identify the clicked row
int rowIndex = Convert.ToInt32(btnDelete.Attributes["RowIndex"]);

GridViewRow gvRow = this.gvEmpInfo.Rows[rowIndex];

//Identify the hidden filed value of clicked row
int emp_gid = Convert.ToInt32(((HiddenField)gvRow.FindControl("hidemp_gid")).Value);

string msg = String.Empty;

try
{
EmployeeInfoBLL objEmployeeInfoBLL = new EmployeeInfoBLL();
msg = objEmployeeInfoBLL.RemoveEmployeeInfo(emp_gid);
Load_gvEmpInfo();
ClearForm();
}
catch (Exception exp)
{
msg = exp.Message;
}

}

protected void btnSave_Click(object sender, EventArgs e)
{
String msg = String.Empty;
Button btnSave = sender as Button;

EmployeeInfoBLL objEmployeeInfoBLL = new EmployeeInfoBLL();
EmployeeInfo objEmployeeInfo = new EmployeeInfo();
objEmployeeInfo.EmpFullNm = this.txtEmpFullNm.Text;
objEmployeeInfo.EmpNickNm = this.txtEmpNickNm.Text;
objEmployeeInfo.EmpDesignation = this.txtDesignation.Text;

try
{
if (btnSave.Text == "Edit")
{
objEmployeeInfo.EmpGid = Convert.ToInt32(this.hf_emp_gid.Value);
msg = objEmployeeInfoBLL.EditEmployeeInfo(objEmployeeInfo);
this.btnSave.Text = "Save";
}
else
{
msg = objEmployeeInfoBLL.SaveEmployeeInfo(objEmployeeInfo);
}

Load_gvEmpInfo();
ClearForm();
}
catch (Exception exp)
{
msg = exp.Message;
}

}

///
/// Clear form
///

private void ClearForm()
{
this.txtEmpFullNm.Text = "";
this.txtEmpNickNm.Text = "";
this.txtDesignation.Text = "";
}
}

Yes! You have done this. Now you will see the following form where you can insert update and delete employee information.
gridView

Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

4 thoughts on “A Simple Demonstration with ASP.net GridView

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>