30 April, 2012

Generate image on the fly

Generating image on the fly is not difficult in asp.net. Here I have created national flag of Bangladesh on the fly and displayed this as JPEG image format in asp.net web form. So let’s start to draw an image on the fly.

Step 1: Add a new web form in ASP.net website.

Step 2: In the Page_Load of the web form write the following code


    protected void Page_Load(object sender, EventArgs e)
    {
        //Define the rectangle with (x co-ordinate, y co-ordinate, width, height)
        RectangleF rectF = new RectangleF(0, 0, 400, 200);
        Bitmap img = new Bitmap(400, 200, PixelFormat.Format24bppRgb);
        Graphics grphs = Graphics.FromImage(img);
        SolidBrush bgBrush = new SolidBrush(System.Drawing.Color.Green);
        
        grphs.FillRectangle(bgBrush, rectF);

        SolidBrush elpsBgBrush = new SolidBrush(System.Drawing.Color.Red);
    
        //Fill the interior of an ellipse by the pair of co-ordinates and height and width 
        grphs.FillEllipse(elpsBgBrush, 140, 40, 130, 130);


        int fontSize = 20;
        string fontName = "Arial" + ".ttf";
        PrivateFontCollection privateFontCollection = new PrivateFontCollection();
        privateFontCollection.AddFontFile(@"C:/WINDOWS/Fonts/" + fontName);

        FontFamily fontFamily = privateFontCollection.Families[0];

        // Set font style
        int fontStyle = Convert.ToInt32(Request.Form.Get("fontstyle"));
        string text = "Bangladesh";

        SolidBrush fgBrush = new SolidBrush(System.Drawing.Color.Yellow);
        FontStyle style = FontStyle.Bold;

        StringFormat format = new StringFormat();
        format.FormatFlags = StringFormatFlags.DirectionRightToLeft;

        Font font = new Font(fontFamily, fontSize, style, GraphicsUnit.Pixel);

        grphs.DrawString(text, font, fgBrush, rectF, format);

        Response.ContentType = "image/jpeg";
        img.Save(Response.OutputStream, ImageFormat.Jpeg);

        // Dispose objects
        img.Dispose();
    }


Here RectangleF stores a set of four floating-point numbers that represent the location and size of a rectangle. Here first pair is (x,y) co-ordinate and second pair is width and height. SolidBrush define a brush of single color. FillRectangle and FillEllipse is responsible for both Filling rectangle and Ellipse. Graphics.DrawString is used to draw text in the rectangle.

Now run the website. Yes! You have drawn your desired National Flag of Bangladesh and its look like this.


29 April, 2012

Retrieve data from database by first ASP.net program

You who are very beginner and want to retrieve data from database, can use the code snippet. Though this is not good practice, this is very useful for beginners. Because beginners is not interested to layer architecture can not create connection string in web.config file. Here, I have create a city_info table and displayed this data into a table of asp page. Ok, no more talk. Lets start.

Step 1: Create a table city_info and insert 3 data in the table.

CREATE TABLE city_info
(
      id INT
      , name VARCHAR(100)
)

insert into city_info
(
id, name
)
values
(
      1    , 'Dhaka'
)

insert into city_info
(
id, name
)
values
(
      2      , 'Chittagong'
)


insert into city_info
(
id, name
)
values
(
      3      , 'Comilla'
)

Step 2: Create a literal control in asp page.

<asp:Literal ID = "ltrlCityInfo" runat = "server">asp:Literal>

Step 3: Accessing data in Page_Load method of asp page and bind data with a table in ltrCityInfo




using System.Data.SqlClient; //Use for SqlConnection, SqlCommand
using System.Data;           //Use for CommandType


protected void Page_Load(object sender, EventArgs e)
{
        
//Connection string, here SOFT is database server name, TestDB is database name, user id and password of //database server
        string connectionString = "Data Source=SOFT;Initial Catalog=TestDB;User ID=sa;Password=sa";
        SqlConnection sqlConn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = sqlConn;


        SqlDataReader rdr = null;

        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select id, name from city_info";

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

            rdr = cmd.ExecuteReader();

            this.ltrlCityInfo.Text = "";
            while (rdr.Read())
            {
                this.ltrlCityInfo.Text += "";
            }

            this.ltrlCityInfo.Text += "
City Name
"; string city = rdr["name"].ToString(); this.ltrlCityInfo.Text += city; this.ltrlCityInfo.Text += "
"; } catch (Exception exp) { throw (exp); } finally { if (sqlConn.State == ConnectionState.Open) sqlConn.Close(); } }

Yes! We have done. After running the project, you will see the following output.

City Name
Dhaka
Chittagong
Comilla

27 April, 2012

Difference between String and StringBuilder

String and StringBuilder class both are used to handle string.
StringBuilder is an immutable class means that you can insert, append and replace without creating a new StringBuilder instance each time.
String is immutable, each time you perform an operation on the string – you are actually creating a new instance of string to replace the old one.
 So according to the discussion, the StringBuilder is more efficient for operations to manipulate strings.
The most common operation with a string is concatenation. When you use the “String” object to concatenate two strings, the first string is combined to the other string by creating a new instance in the memory and then the old string is deleted.
When you make a “StringBuilder” object for concatenation the Append method is used which is perform insertion operation on the existing string. So, StringBuilder is more efficient in case of large amounts of string manipulation.

Have a look on the following code snippet.
string str = string.Empty;
for (int i = 0; i < 1000; i++) {
  str += i.ToString() + " ";
}

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
  sb.Append(i);
  sb.Append(' ');
}


Now think, which one is faster?  Right! The second one. Because, for the first snippet, every time new instance of string is created and the for the second one, StringBuilder instance is created only at once.

Display information by ASP.net Literal Control

The literal control is similar to the Label control. Unlike the Label control, the Literal control does not render its content inside of a tag. You can use the Literal control to display text or HTML content in a browser.

Literal control does not support either CssClass or BackColor properties.

Literal control has mode property which Label has not.
Three mode property of Literal control:
  1. PassThrough: Displays the contents of the control without encoding.
  2. Encode: The contents of the control are converted to an HTML-encoded string.
  3. Transform: Unsupported markup-language elements are removed from the contents of the control. If the Literal control is rendered on a browser that supports HTML or XHTML, the control's contents are not modified.

You will be clear after watching output of the following

Write the following code in your aspx page. Here I used 4 literal. 1st one for displaying simple message from code behind. Others 3 are displayed the content in different mode of literal.

<asp:Literal ID = "ltrlMsg" runat = "server">asp:Literal>
<br />
<asp:Literal ID = "ltrPasThrough" Mode ="PassThrough" Text = "This is Mahedee Hasan" runat = "server">asp:Literal>
<br />
<asp:Literal ID = "Literal1" Mode="Encode" Text = "This is Mahedee Hasan" runat = "server">asp:Literal>
<br />
<asp:Literal ID = "Literal2" Mode = "Transform" Text = "This is Mahedee Hasan" runat = "server">asp:Literal>

<br />

protected void Page_Load(object sender, EventArgs e)
{
    this.ltrlMsg.Text = "Welcome to ASP.net Literal Control!";
}


The output of the code is look like this.

Welcome to ASP.net Literal Control!
This is Mahedee Hasan
<b> <i>This is Mahedee Hasanl</i>l</b> 
This is Mahedee Hasan

Call JavaScript from Asp.net code behind

Suppose you want to display confirmation message by javascript from asp.net code behind after saving data. Write the following code in your button event.

protected void btnSaved_Click(object sender, EventArgs e)
{

         string msg = "Data saved sucessfully";
         Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script type=text/javascript<alert('" + msg + "')</script>");


}

Determine whether Caps Lock is on in ASP.net Page by JavaScript


Here I used a simple Textbox in ASP.net page and used Javascript to determine whether Caps Lock is on or off.
I have used the following Javascript code in between head  tag.
 function isCapslock(e) {

            e = (e) ? e : window.event;

            var charCode = false;

            if (e.which) {
                charCode = e.which;
            } else if (e.keyCode) {
                charCode = e.keyCode;
            }

            var shifton = false;
            if (e.shiftKey) {
                shifton = e.shiftKey;
            } else if (e.modifiers) {
                shifton = !!(e.modifiers & 4);
            }

            if (charCode >= 97 && charCode <= 122 && shifton) {
                document.getElementById("txtCapsMsg").value = "Caps Lock is on";
                return true;
            }

            if (charCode >= 65 && charCode <= 90 && !shifton) {
                document.getElementById("txtCapsMsg").value = "Caps Lock is on";
                return true;
            }

            document.getElementById("txtCapsMsg").value = "Caps Lock is off";
            return false;

        }

I have also used two text box in ASP.net page. One for input and another for displaying message whether Caps Lock is on or off.


<form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Message :
                td>
                <td>
                    <input type="text" id="txtCapsMsg" />
                td>
            tr>
            <tr>
                <td>
                    Input Text :
                td>
                <td>
                    <asp:TextBox ID="txtInputCaps" runat="server" onkeypress="isCapslock(event)">asp:TextBox>
                td>
            tr>
        table>
    div>
    form>

Now input some text in input textbox. Message will be showed in txtCapsMsg textbox whether Caps Lock is on or off.

23 April, 2012

Retrieve Store Procedure's Output parameter by C# (ASP.net)

How to retrieve store procedure's output parameter by C#? Here I have explained with a simple example. I created a simple store procedure with output parameter. Then I catch it from code behind page of asp.net and displayed it to a label. Here I used a class DBConnector to connect with database. Lets look on the demo.

Step 1: Set connection string in web.config.
       
            
       
     
Step 2: Create a store procedure with output parameter.
CREATE PROCEDURE [dbo].[sp_output_param]
(
     @input_param VARCHAR(200)
    , @Response VARCHAR(250) OUTPUT
)
AS
    --DECLARE @myName


BEGIN
    
    SET @Response = 'Welcome ' + @input_param
    
END

Step 3: Create a DBConnector Class to retrieve data from database.
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 4 : Create a label name lblMsg in asp page. Then in a button event, write the following code. You will see your desired output in the lebel which is actually the value of output parameter. Here btnGetOutputParam_Click is the click event of Button btnGetOutputParam.
protected void btnGetOutputParam_Click(object sender, EventArgs e)
{
        SqlConnection sqlConn;
        SqlCommand cmd;

        DBConnector objDBConnector = new DBConnector();
        sqlConn = objDBConnector.GetConn();

        cmd = objDBConnector.GetCommand();

        SqlDataReader rdr = null;

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "sp_output_param";
        cmd.Parameters.AddWithValue("@input_param", "Mahedee");
        cmd.Parameters.Add("@Response", SqlDbType.VarChar, 250);
        cmd.Parameters["@Response"].Direction = ParameterDirection.Output;

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

            rdr = cmd.ExecuteReader();

            string outputValue = cmd.Parameters["@Response"].Value.ToString();
            this.lblMsg.Text = outputValue;
        }
        catch (Exception exp)
        {
            throw (exp);
        }
        finally
        {
            if (sqlConn.State == ConnectionState.Open)
                sqlConn.Close();
        }

    }

You will see in label - Welcome Mahedee which is provided by output parameter of store procedure.

Simple Queries in SQL Server


  •  Get Column Name, Data Type and Data Length of a table. Here hrm_employee is a table name.

SELECT COLUMN_NAME 'Column Name',

DATA_TYPE 'Data Type',

CHARACTER_MAXIMUM_LENGTH 'Maximum Length'

FROM information_schema.columns

WHERE TABLE_NAME = 'hrm_employee'


After executing the query, you will see all column name of hrm_employee table with data type and length.

21 April, 2012

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 void SetMainConnectionString()
    {
        connectionString = ConfigurationManager.ConnectionStrings["BlueChipConnectionString"].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.



Click here to download demo project.  Before running the project please run the sql mentioned in step - 1