A Simple Demonstration with ASP.Net GridView

7 minute read

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.

<connectionStrings>
  <add name="SQLServerConnectionString" connectionString="Data Source=SOFT;Initial   Catalog=TestDB;User ID=sa;Password=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>

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

<table>
        <tr>
            <td align="right">
                Full Name :
            </td>
            <td>
                <asp:TextBox ID="txtEmpFullNm" Width ="200px" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="right">
                Nick Name :
            </td>
            <td>
                <asp:TextBox ID="txtEmpNickNm" Width ="200px" runat="server"></asp:TextBox>
            </td>
        </tr>
 
        <tr>
            <td align="right">
                Designation :
            </td>
            <td>
                <asp:TextBox ID="txtDesignation" runat="server"
                    Width="200px"></asp:TextBox>
            </td>
        </tr>
    </table>
 
    <asp:Button ID = "btnSave" runat = "server" Text ="Save" Height="23px" 
        style="font-weight: 700" Width="100px" onclick="btnSave_Click" />
 
        <asp:HiddenField ID ="hf_emp_gid" runat ="server" />
    <br />
    <br />
    <asp:GridView ID="gvEmpInfo" runat="server" AutoGenerateColumns="False" CellPadding="4"
        ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="emp_fullnm" HeaderText="Full Name" />
            <asp:BoundField DataField="emp_nicknm" HeaderText="Nick Name" />
            <asp:BoundField DataField="emp_designation" HeaderText="Designation" />
            <asp:TemplateField HeaderText="Edit">
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="80px" />
                <ItemTemplate>
                    <asp:HiddenField ID="hidemp_gid" runat="server" Value='<%#Eval("emp_gid") %>' />
                    <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CausesValidation="false"
                        RowIndex='<%# Container.DisplayIndex %>' OnClick="btnEdit_Click">
                            <img style="border:none;" src = "Images/edit_icon.gif"/></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="80px" />
                <ItemTemplate>
                    <asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CausesValidation="false"
                        RowIndex='<%# Container.DisplayIndex %>' OnClick="btnDelete_Click">
                            <img style="border:none;" src = "Images/icon_remove.png"/></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>

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

Source code