Tuesday, 28 June 2016

Encapsulation and Abstraction in a simple way.

I will try to demonstrate Encapsulation and Abstraction in a simple way.. Lets see..

The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.
Encapsulation is -

Hiding Complexity,
Binding Data and Function together,
Making Complicated Method's Private,
Making Instance Variable's Private,
Hiding Unnecessary Data and Functions from End User.
Encapsulation implements Abstraction.

And Abstraction is -

Showing Whats Necessary,
Data needs to abstract from End User,
Lets see an example-

The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".

By looking at the Image we can say that we need a Customer Class.

Step - 1: What does my Customer Class needs?

i.e.

2 variables to store Customer Code and Customer Name.

1 Function to Add the Customer Code and Customer Name into Database.

  namespace CustomerContent
    {
       public class Customer
       {
           public string CustomerCode = "";
           public string CustomerName = "";
           public void ADD()
           {
              //my DB code will go here
           }
Now only ADD method wont work here alone.

Step -2: How will the validation work, ADD Function act?

We will need Database Connection code and Validation Code (Extra Methods).

     public bool Validate()
     {
    //Granular Customer Code and Name
    return true;
     }

     public bool CreateDBObject()
     {
    //DB Connection Code
    return true;
     }

class Program
{
   static void main(String[] args)
   {
     CustomerComponent.Customer obj = new CustomerComponent.Customer;

     obj.CustomerCode = "s001";
     obj.CustomerName = "Mac";

     obj.Validate();
     obj.CreateDBObject();

     obj.ADD();
    }
}
Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.

Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.

So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.

In other words Simplifying Interface to End User is Encapsulation.

So now the complete code looks like as below -

namespace CustomerContent
{
     public class Customer
     {
        public string CustomerCode = "";
        public string CustomerName = "";

        public void ADD()
        {
           //my DB code will go here
        }

        private bool Validate()
        {
           //Granular Customer Code and Name
           return true;
        }

        private bool CreateDBObject()
        {
           //DB Connection Code
           return true;
        }

  class Program
  {
     static void main(String[] args)
     {
        CustomerComponent.Customer obj = new CustomerComponent.Customer;

        obj.CustomerCode = "s001";

        obj.CustomerName = "Mac";

        obj.ADD();
   }
}
Summary :

Step -1: What does my Customer Class needs? is Abstraction.

Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.

P.S. - The code above is hard and fast.

Thursday, 16 June 2016

Differrnce between Primary Key, Unique Key & Foreign Key

Primary Key

Primary key cannot have a NULL value.
Each table can have only one primary key.
By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.
Primary key can be related with another table's as a Foreign Key.
We can generated ID automatically with the help of Auto Increment field. Primary key supports Auto Increment value.

Unique Key

Unique Constraint may have a NULL value.
Each table can have more than one Unique Constraint.
By default, Unique key is a unique non-clustered index.
Unique Constraint can not be related with another table's as a Foreign Key.
Unique Constraint doesn't supports Auto Increment value.

Foreign Key

Foreign key is a field in the table that is primary key in another table.
Foreign key can accept multiple null value.
Foreign key do not automatically create an index, clustered or non-clustered. You can manually create an index on foreign key.
We can have more than one foreign key in a table.
There are actual advantages to having a foreign key be supported with a clustered index, but you get only one per table. What's the advantage? If you are selecting the parent plus all child records, you want the child records next to each other. This is easy to accomplish using a clustered index.
Having a null foreign key is usually a bad idea. In the example below, the record in [dbo].[child] is what would be referred to as an "orphan record". Think long and hard before doing this.

Difference between Union and Union All

1. UNION removes duplicate rows.

“UNION ALL” does not remove the duplicate row. It returns all from all queries.

2. UNION uses a distinct sort.

“UNION ALL” does not use a distinct sort, so the performance of “UNION ALL” is slightly higher than “UNION”.

3. UNION cannot work with a column that has a TEXT data type.

UNION ALL can work with all data type columns.

Monday, 13 June 2016

Multiple Inheritance With Interfaces

Introduction

This article gives an idea about the situation called interface clash. This situation occurs when two interfaces have functions with the same name and signature and one base class implements these interfaces.

Background

In earlier languages like C++, there was the concept of Multiple Inheritance. But in C#, we do not have any such feature. This was something in the list of features which is available in C++ but not in C#. Due to this feature in C++, developers were facing the problem of Diamond Inheritance. That’s why Virtual Functions came into the picture.

Using the Code

In C#, when two interfaces have functions with the same name and a class implements these interfaces, then we have to specifically handle this situation. We have to tell the compiler which class function we want to implement. For such cases, we have to use the name of the interface during function implementation. Have a look at the following example:

Blocks of code should be set as style Formatted like this:

Ex:
    /// <summary />
    /// Interface 1
    /// </summary />
    public interface Interface1
    {
        /// <summary />
        /// Function with the same name as Interface 2
        /// </summary />
        void MyInterfaceFunction();
    }

    /// <summary />
    /// Interface 2
    /// </summary />
    public interface Interface2
    {
        /// <summary />
        /// Function with the same name as Interface 1
        /// </summary />
        void MyInterfaceFunction();
    }

    /// <summary />
    /// MyTestBaseClass Implements the two interfaces Interface1 and Interface2
    /// </summary />
    public class MyTestBaseClass:Interface1,Interface2
    {
        #region Interface1 Members

        void Interface1.MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyInterface1 Function()");
            return;
        }

        #endregion

        #region Interface2 Members

        void Interface2.MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyInterface2 Function()");
            return;
        }

        #endregion
    }

In the above example, we are implementing the function MyInterfaceFunction() by using its interface name. In this case if we create the object of MyTestBaseClass and check for MyInterfaceFunction(), it won't be directly available. Look at the following code:

MyTestBaseClass obj = new MyTestBaseClass();
//Following code would give an error saying that
//class does not have a definition for MyInterfaceFunction.
obj.MyInterfaceFunction();

We can call the respective interface function by typecasting it to the corresponding interfaces. See the example below:

//This code would work fine and calls the function of the first interface
((Interface1)obj).MyInterfaceFunction();

//This code would also work fine and calls the function of the second interface
((Interface2)obj).MyInterfaceFunction();

Now comes the twist. We will add one more function with the same name in MyTestBaseClass. Now try to access the elements of the object of MyTestBaseClass. You will see that MyInterfaceFunction is available there. See the following code now and this code would call the function of interfaces first followed by the Class function.

Ex.
    /// <summary />
    /// MyTestBaseClass implements the two interfaces Interface1 and Interface2
    /// </summary />
    public class MyTestBaseClass:Interface1,Interface2
    {
        public void MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyTestBaseClass's Function()");
            return;
        }

        #region Interface1 Members

        void Interface1.MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyInterface1 Function()");
            return;
        }

        #endregion

        #region Interface2 Members

        void Interface2.MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyInterface2 Function()");
            return;
        }

        #endregion
    }

    /// <summary />
    /// Interface 1
    /// </summary />
    public interface Interface1
    {
        /// <summary />
        /// Function with Same Name as Interface 2
        /// </summary />
        void MyInterfaceFunction();
    }

    /// <summary />
    /// Interface 2
    /// </summary />
    public interface Interface2
    {
        /// <summary />
        /// Function with Same Name as Interface 1
        /// </summary />
        void MyInterfaceFunction();
    }

In the Main Function –

MyTestBaseClass obj = new MyTestBaseClass();

//This code would work fine and calls the function of the first interface
((Interface1)obj).MyInterfaceFunction();

//This code would work fine and calls the function of the second interface
((Interface2)obj).MyInterfaceFunction();

//This code would call the class function
obj.MyInterfaceFunction();
Now comes another twist. You derive a class MyDerivedClass() from MyTestBaseClass(). Before that, remove the function last implemented in MyTestBaseClass(). Now create the instance of MyDerivedClass() and check. No function would be available with this class even though its base class is having these functions.

Ex:
    /// <summary />
    /// Interface 1
    /// </summary />
    public interface Interface1
    {
        /// <summary />
        /// Function with the same name as Interface 2
        /// </summary />
        void MyInterfaceFunction();
    }

    /// <summary />
    /// Interface 2
    /// </summary />
    public interface Interface2
    {
        /// <summary />
        /// Function with the same name as Interface 1
        /// </summary />
        void MyInterfaceFunction();
    }

    /// <summary />
    /// MyTestBaseClass implements the two interfaces Interface1 and Interface2
    /// </summary />
    public class MyTestBaseClass:Interface1,Interface2
    {

        //public void MyInterfaceFunction()
        //{
        //    MessageBox.Show("Frm MyTestBaseClass's Function()");
        //    return;
        //}

        #region Interface1 Members

        void Interface1.MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyInterface1 Function()");
            return;
        }

        #endregion

        #region Interface2 Members

        void Interface2.MyInterfaceFunction()
        {
            MessageBox.Show("Frm MyInterface2 Function()");
            return;
        }

        #endregion
    }

    /// <summary />
    /// New Derived class which is derived from MyTestBaseClass
    /// </summary />
    public class MyDerivedClass : MyTestBaseClass
    {
        //No Functions Here....
    }
So again here for getting the function of interfaces, we have to separately typecast the object of the derived class with the interface. See the code below:

//In the Main Function……

//This code would call the Interface1 function
MyDerivedClass derivedObj = new MyDerivedClass();
((Interface1)derivedObj).MyInterfaceFunction();       

Conclusion
From the above article, you should get an idea about calling interface functions when there is a clash. Your suggestions and views will be appreciated.

Monday, 30 May 2016

Difference Between Stored Procedure andUser Defined Function in SQL Server

Stored Procedure

A Stored Procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a Stored Procedure and then just call the Stored Procedure to execute the SQL code that you saved as part of the Stored Procedure.

In addition to running the same SQL code over and over again you also have the ability to pass parameters to the Stored Procedure, so depending on what the need is, the Stored Procedure can act accordingly based on the parameter values that were passed.

Stored Procedures can also improve performance. Many tasks are implemented as a series of SQL statements. Conditional logic applied to the results of the first SQL statements determine which subsequent SQL statements are executed. If these SQL statements and conditional logic are written into a Stored Procedure, they become part of a single execution plan on the server. The results do not need to be returned to the client to have the conditional logic applied; all of the work is done on the server.

Benefits of Stored Procedures

Precompiled execution: SQL Server compiles each Stored Procedure once and then reutilizes the execution plan. This results in tremendous performance boosts when Stored Procedures are called repeatedly.

Reduced client/server traffic: If network bandwidth is a concern in your environment then you'll be happy to learn that Stored Procedures can reduce long SQL queries to a single line that is transmitted over the wire.

Efficient reuse of code and programming abstraction: Stored Procedures can be used by multiple users and client programs. If you utilize them in a planned manner then you'll find the development cycle requires less time.

Enhanced security controls: You can grant users permission to execute a Stored Procedure independently of underlying table permissions.
User Defined Functions

Like functions in programming languages, SQL Server User Defined Functions are routines that accept parameters, perform an action such as a complex calculation, and returns the result of that action as a value. The return value can either be a single scalar value or a result set.

Functions in programming languages are subroutines used to encapsulate frequently performed logic. Any code that must perform the logic incorporated in a function can call the function rather than having to repeat all of the function logic.

SQL Server supports two types of functions

Built-in functions: Operate as defined in the Transact-SQL Reference and cannot be modified. The functions can be referenced only in Transact-SQL statements using the syntax defined in the Transact-SQL Reference.

User Defined Functions: Allow you to define your own Transact-SQL functions using the CREATE FUNCTION statement. User Defined Functions use zero or more input parameters, and return a single value. Some User Defined Functions return a single, scalar data value, such as an int, char, or decimal value.
Benefits of User Defined Functions

They allow modular programming: You can create the function once, store it in the database, and call it any number of times in your program. User Defined Functions can be modified independently of the program source code.

They allow faster execution: Similar to Stored Procedures, Transact-SQL User Defined Functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic.

Transact-SQL functions are better suited for data-access intensive logic.
They can reduce network traffic: An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Differences between Stored Procedure and User Defined Function in SQL Server

Sr.No.User Defined FunctionStored Procedure
1 Function must return a value.Stored Procedure may or not return values.

2Will allow only Select statements, it will not allow us to use DML statements.Can have select statements as well as DML statements such as insert, update, delete and so on

3 It will allow only input parameters, doesn't support output parameters.It can have both input and output parameters.
4It will not allow us to use try-catch blocks.For exception handling we can use try catch blocks.

5Transactions are not allowed within functions.Can use transactions within Stored Procedures.

6We can use only table variables, it will not allow using temporary tables.Can use both table variables as well as temporary table in it.

7Stored Procedures can't be called from a function.Stored Procedures can call functions.

8 Functions can be called from a select statement.Procedures can't be called from Select/Where/Having and so on statements. Execute/Exec statement can be used to call/execute Stored Procedure.

9A UDF can be used in join clause as a result set.Procedures can't be used in Join clause

Wednesday, 18 May 2016

Pivot table in sql

Simple Way To Use Pivot In SQL Query
Maksud Saifullah Pulak, 4 Dec 2015 CPOL

    4.70 (75 votes)
Rate this:
vote 1vote 2vote 3vote 4vote 5
Transforming data from row-level data to columnar data.
Introduction
This is a very simple example of Pivot query for the beginners. We use pivot queries when we need to transform data from row-level to columnar data.

Pivot query help us to generate an interactive table that quickly combines and compares large amounts of data. We can rotate its rows and columns to see different summaries of the source data, and we can display the details for areas of interest at a glance. It also help us to generate Multidimensional reporting.

Background
This post intends to help T-SQL developers get started with PIVOT queries. Most business applications will need some sort of PIVOT queries and I am sure many of you must have come across pivoting requirements several times in the past.

Using the Code
Let us have a table name Invoice which has three properties, InvoiceNumber, InvoiceDate, InvoiceAmount. Suppose we have several rows input in the table. Our goal is to display the sum of InvoiceAmount each month.

Hide   Copy Code
SELECT * FROM (SELECT year(invoiceDate) as [year], left(datename(month,invoicedate),3)as [month], _
InvoiceAmount as Amount FROM Invoice) as InvoiceResult

Hide   Copy Code
SELECT *
FROM (
    SELECT
        year(invoiceDate) as [year],left(datename(month,invoicedate),3)as [month],
        InvoiceAmount as Amount
    FROM Invoice
) as s
PIVOT
(
    SUM(Amount)
    FOR [month] IN (jan, feb, mar, apr,
    may, jun, jul, aug, sep, oct, nov, dec)
)AS pvt

License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

ADO.NET DataView in ASP.NET

ADO.NET DataView in ASP.NET
By Rohatash Kumar on Feb 01, 2012
A DataView provides various views of the data stored in a DataTable. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.

A DataView provides various views of the data stored in a DataTable. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression. That is we can customize the views of data from a DataTable.

Creating Table in SQL Server Database

Now create a table named UserDetail with the columns UserID and UserName. The table looks like as below.

Now insert some data into the table.

Now creating a new web application project in Visual Studio 2010. Now add the following namespace.

using System.Data.SqlClient;
using System.Data;

Now write the connection string to connect to the database.

string strConnection = "Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;";

Here in aspx code, I used a DataGrid.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication120.WebForm1" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div> 
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>  
    </div>
    </form>
</body>
</html>

Now we create a simple application showing the SQL Server Table Data in the GridView. The following code is the simple code without using DataView.

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

namespace WebApplication120
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            show();
        }
        private void show()
        {
            {
                SqlConnection con = new SqlConnection("Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;");
                string strSQL = "Select * from UserDetail";
                SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
                DataSet ds = new DataSet();
                dt.Fill(ds, "UserDetail");
                con.Close();
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }
}

Creating a DataView

To convert a DataSet to a DataView in ASP.Net using C# code, you can initialize the DataView class object by accessing the DefaultView property via DataTable collection of DataSet. DefaultView property enables you to convert the DataSet to DataView.

SqlConnection con = new SqlConnection("Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;");
                string strSQL = "Select * from UserDetail";
                SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
                DataSet ds = new DataSet();
                dt.Fill(ds, "UserDetail");
                con.Close();
                DataView dv = new DataView();              
                GridView1.DataSource = ds.Tables[0].DefaultView;
                GridView1.DataBind();

Now run the application.

Adding new row in the DataView

We can add new rows in the DataView using AddNew() method in the DataView. The following C# source code shows how to add a new row in a DataView.

SqlConnection con = new SqlConnection("Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;");
                string strSQL = "Select * from UserDetail";
                SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
           

Monday, 16 May 2016

Email and Mobile No Validations in asp.net

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="Test_Website_13_12_2015._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script  type="text/javascript" >
    function validateEmail_Ext() {

   
    }

    function validateTxt() {
        var obj = document.getElementById('<%= txtEmail.ClientID %>');
        var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
        if (regex.test(obj.value)) {
            //You can also assign stylesheet by
            //obj.className='....';
            obj.style.backgroundColor = '';
            obj.style.backgroundColor = '';
            alert("valid Email Address");
        }
        else {
            //Changing Background Color, so that user can understand that its invalid
            //You can also assign stylesheet by
            //obj.className='....';
            alert("please enter valid email");
            obj.style.backgroundColor = '#FD5E53';
            obj.style.borderColor = '#CD4A4A';
            return false;
        }

        var inputtxt = document.getElementById('<%= TxtPhone.ClientID  %>');
        //     var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{8})$/;
               var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{8})$/;
  if(inputtxt.value.match(phoneno)) {
      alert("valid Phone Number");
         
     }
   else {
       inputtxt.style.backgroundColor = '#FD5E53';
       inputtxt.style.borderColor = '#CD4A4A';
         alert("Not a valid Phone Number");
       return false;
     }

   return true;

    }
</script>
</asp:Content>

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

    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>

   <asp:TextBox ID='txtEmail' runat="server" placeholder="demo@demo.com"></asp:TextBox>
   <br />
   <asp:TextBox ID='TxtPhone' runat="server" placeholder="022-252-12345678"></asp:TextBox>
   <br />
<%--<asp:Button id="cmdTest" runat="server" Text="Check Email Address" OnClientClick="validateEmail();" /><br />--%>
<asp:Button id="cmdTest_Ext" runat="server" Text="Save" OnClientClick="return validateTxt();" />

<p>

</p>
</asp:Content>

Tuesday, 10 May 2016

Software Development Life Cycle ( SDLC )


Software Development Life Cycle, SDLC for short, is a well-defined, structured sequence of stages in software engineering to develop the intended software product.


SDLC Activities:

SDLC provides a series of steps to be followed to design and develop a software product efficiently. SDLC framework includes the following steps:



Communication:
This is the first step where the user initiates the request for a desired software product. He contacts the serviceprovider and tries to negotiate the terms. He submits his request to the service providing organization in writing.


Requirement Gathering:
This step onwards the software development team works to carry on the project. The team holds discussions with various stakeholders from problem domain and tries to bring out as much information as possible on their requirements. The requirements are contemplated and segregated into user requirements, system requirements and functional requirements. The requirements are collected using a number of practices as given -studying the existing or obsolete system and software,conducting interviews of users and developers,referring to the database orcollecting answers from the questionnaires.







Tuesday, 3 May 2016

want to Find Control in gridview on RowCommand event in asp.net

Dear All

I want to Find Control in gridview on RowCommand event in asp.net
if it Is possible Please revert me

Reply | Reply with Attachment
Alert Moderator
Responses

Posted by: Prabhakar on: 5/10/2011 [Member] [MVP] Starter | Points: 25

0

Hi avalemanoj0405

i am Provide Code For Find Control ... Check it now. . . it's a use full for you . . on RowDataBound

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            Label lblPrice = (Label)e.Row.FindControl("lblPrice");

            Label lblUnitsInStock = (Label)e.Row.FindControl("lblUnitsInStock");

            decimal price = Decimal.Parse(lblPrice.Text);

            decimal stock = Decimal.Parse(lblUnitsInStock.Text);

            totalPrice += price;

            totalStock += stock;

            totalItems += 1;

        }

        if (e.Row.RowType == DataControlRowType.Footer)

        {

            Label lblTotalPrice = (Label)e.Row.FindControl("lblTotalPrice");

            Label lblTotalUnitsInStock = (Label)e.Row.FindControl("lblTotalUnitsInStock");

            lblTotalPrice.Text = totalPrice.ToString();

            lblTotalUnitsInStock.Text = totalStock.ToString();

            lblAveragePrice.Text = (totalPrice / totalItems).ToString("F");

        }

    }

Best Regard's
Prabhakar

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Navalemanoj0405 on: 5/10/2011 [Member] Starter | Points: 25

0

thanks for reply prabhakar
but i want to find control on RowCommand of gridview.

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Prabhakar on: 5/10/2011 [Member] [MVP] Starter | Points: 25

0

ok Navalemanoj0405

check this code. . if u agree mark as Answer . .

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

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

        {

            int state = 0;

            int index = int.Parse(e.CommandArgument.ToString());

            GridViewRow row = GridView1.Rows[index];

            DropDownList lstState = (DropDownList)row.FindControl("StateID");

            state = int.Parse(lstState.SelectedValue.ToString());

            ObjectDataSource1.UpdateParameters.Add("StateID", state.ToString());

        }     

    }

Best Regard's
Prabhakar

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Navalemanoj0405 on: 5/10/2011 [Member] Starter | Points: 25

0

hey prabhakar but what should be there in CommandArgument in gridview ?

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Prabhakar on: 5/10/2011 [Member] [MVP] Starter | Points: 25

0

Hi

here the Command-argument To determine the index of the row that raised the event, use the CommandArgument property of the event argument that is passed to the event.

Best Regard's
Prabhakar

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Navalemanoj0405 on: 5/10/2011 [Member] Starter | Points: 25

0

Hi
CommandArgument giving me empty string
What i should do?

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Prabhakar on: 5/10/2011 [Member] [MVP] Starter | Points: 25

0

Hi..

if u click on Add or update button so CommandArgument given not empty . . Show ur code else . . Check this link . .

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx#Y2793

Best Regard's
Prabhakar

Navalemanoj0405, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ndebata on: 5/10/2011 [Member] Starter | Points: 25

Getting Textbox value in Javascript

I am trying to get the value of the textbox in a javascript, but its not working. Given below is the code of my test page

<%@ Page Title="" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeFile="test3.aspx.vb" Inherits="test3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
<script language="javascript">

    function GetAlert() {

        var TestVar = document.getElementById('txt_model_code').value;
        alert(TestVar);

    }

</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:TextBox ID="txt_model_code" runat="server" ></asp:TextBox><br /><br />

<input type="button" value="db Function" onclick="GetAlert()" /><br />
</asp:Content>
So where am i going wrong?? How to get the text entered in the textbox in the javascript???

share improve this question
Asked
Feb 18 '11 at 9:22

Shijilal
819●6●20●39
6  
do this: var TestVar = document.getElementById('<%= txt_model_code.ClientID %>').value; – deostroll Feb 18 '11 at 9:25
   
@deostroll thanks it worked.. Now what to do if i want to show that value in another textbox – Shijilal Feb 18 '11 at 9:42
2  
document.getElementById('<%= anothertextboxid.ClientID %>').value=TestVar – Nirmal Feb 18 '11 at 9:48
   
as it is asp.net control, you can not get the value using getElementById(). because asp.net controls are converted to html controls and "id" changes on the browser. for more details refer: coding-issues.blogspot.in/2013/10/… – Ranadheer Reddy Oct 31 '13 at 9:36
add a comment
6 Answers order by 
up vote
11
down vote
accepted
Use

document.getElementById('<%= txt_model_code.ClientID %>')
instead of

document.getElementById('txt_model_code')`
Also you can use onClientClick instead of onClick.

share improve this answer
Answered
Feb 18 '11 at 9:38

Nirmal
965●7●25 Edited
Jun 7 '13 at 15:20

David L
13.5k●3●18●43
   
when i use the function in text_model_code onTextChange, it's saying the function is not part of my aspx file.. Why??? <asp:TextBox ID="txt_model_code" runat="server" OnTextChanged="GetModelPageMethod()"> – Shijilal Feb 18 '11 at 10:03
1  
I think you need to use this in onChange="GetModelPageMethod();" – Nirmal Feb 18 '11 at 10:07
   
ohk thanks..it worked – Shijilal Feb 18 '11 at 10:15
add a comment
up vote
4
down vote
This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like

ctl00_ContentColumn_txt_model_code

There are a few ways round this:

Use the actual control name:

var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;

use the ClientID property within ASP script tags

document.getElementById('<%= txt_model_code.ClientID %>').value;

Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.

http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1

Sunday, 3 April 2016

Insert, Delete, Update in GridView in ASP.Net using C#

ASP.NET GridView is a very common and useful control. Here, I’m explaining how to work with GridView control inASP.NET, like how to insert, delete and update record in GridView control. Follow bellow steps to know how to work withGridView in ASP.NET.
Step 1:- Create Database in SqlServer and create a table within this database. For demonstration here I have created database named “Demo” and table named “GridView”
CREATE DATABASE DEMO
GO

USE DEMO
GO

CREATE TABLE GridView
(
id INT PRIMARY KEY IDENTITY,
name VARCHAR (50) NOT NULL,
age INT NOT NULL,
salary FLOAT NOT NULL,
country VARCHAR(50) NOT NULL,
city VARCHAR(50) NOT NULL,
photopath VARCHAR(500) NULL
)
GO

Insert, Delete, Update in GridView in ASP.Net using C#
Note: Here “id” columnis auto increment and primary key. 
Step 2:- Add connection string in your application’s web.config file and change name and connectionString according your SQL Server configuration as following.
<configuration>
     <connectionStrings>
                <add name="dbconnection" providerName="System.Data.SqlClient"
                    connectionString="Data Source=.;Initial Catalog=demo; User Id=xyz; password=123456" />
                </connectionStrings>
</configuration>

Step 3:- Drag & drop GridView controlfrom Toolboxon “.aspx”page and write down the following line of code within <asp:GridView> section or simple copy the following line of code and put where you want to display GridVIew.

<div>
        <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True"
            AutoGenerateColumns="False" onrowdeleting="RowDeleting"
            OnRowCancelingEdit="cancelRecord" OnRowEditing="editRecord"
            OnRowUpdating="updateRecord" CellPadding="4"
            EnableModelValidation="True" GridLines="None" Width="1297px"
            ForeColor="#333333" >
            <RowStyle HorizontalAlign="Center" />
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />

            <Columns>

            <asp:TemplateField>
            <HeaderTemplate>Id</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID ="lblId" runat="server" Text='<%#Bind("id")%>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Name</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID ="lblName" runat="server" Text='<%#Bind("name") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("name") %>' MaxLength="50"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtName" runat="server" Text="*" ToolTip="Enter name"ControlToValidate="txtName"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtName" runat="server" Text="*" ToolTip="Enter alphabate "ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>
           
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewName" runat="server" MaxLength="50"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewName" runat="server" Text="*" ToolTip="Enter name"ControlToValidate="txtNewName"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtNewName" runat="server" Text="*" ToolTip="Enter alphabate "ControlToValidate="txtNewName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>
          
            </FooterTemplate>
            </asp:TemplateField>
           
            <asp:TemplateField>
            <HeaderTemplate>Age</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID="lblAge" runat ="server" Text='<%#Bind("age") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID ="txtAge" runat="server" Text='<%#Bind("age") %>' MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtAge" runat="server" Text="*" ToolTip="Enter age"ControlToValidate="txtAge"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtAge" runat="server" Text="*" ToolTip="Enter numeric value"ControlToValidate="txtAge" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>
          
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewAge" runat="server" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewAge" runat="server" Text="*" ToolTip="Enter age"ControlToValidate="txtNewAge"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revNewtxtAge" runat="server" Text="*" ToolTip="Enter numeric value"ControlToValidate="txtNewAge" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Salary</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID = "lblSalary" runat="server" Text='<%#Bind("salary") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID="txtSalary" runat="server" Text='<%#Bind("salary") %>'  MaxLength="10"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtSalary" runat="server" Text="*"  ToolTip="Enter salary"ControlToValidate="txtSalary"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtSalary" runat="server" Text="*" ToolTip="Enter numeric value"ControlToValidate="txtSalary" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>
          
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewSalary" runat="server" MaxLength="10"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewSalary" runat="server" Text="*"  ToolTip="Enter salary"ControlToValidate="txtNewSalary"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtNewSalary" runat="server" Text="*" ToolTip="Enter numeric value"ControlToValidate="txtNewSalary" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Country</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID = "lblCountry" runat="server" Text='<%#Bind("country") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID="txtCountry" runat="server" Text='<%#Bind("country") %>' MaxLength="20"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtCountry" runat="server" Text="*" ToolTip="Enter country"ControlToValidate="txtCountry"></asp:RequiredFieldValidator>
        
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewCountry" runat="server" MaxLength="20"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewCountry" runat="server" Text="*" ToolTip="Enter country"ControlToValidate="txtNewCountry"></asp:RequiredFieldValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>City</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID = "lblCity" runat="server" Text='<%#Bind("city") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID="txtCity" runat="server" Text='<%#Bind("city") %>' MaxLength="20"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtCity" runat="server" Text="*" ToolTip="Enter city"ControlToValidate="txtCity"></asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewCity" runat="server" MaxLength="20"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewCity" runat="server" Text="*" ToolTip="Enter city"ControlToValidate="txtNewCity"></asp:RequiredFieldValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Photo</HeaderTemplate>
            <ItemTemplate>
            <asp:Image ID="imgPhoto" Width="100px" Height="100px" runat="server" text="Photo"ImageUrl='<%#Bind("photopath") %>' />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:FileUpload ID="fuPhoto" runat="server" ToolTip="select Employee Photo"/>
            <asp:RegularExpressionValidator ID="revfuPhoto" runat="server" Text="*" ToolTip="Image formate only"ControlToValidate="fuPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>
            </EditItemTemplate>
            <FooterTemplate>
            <asp:FileUpload ID="fuNewPhoto" runat="server" ToolTip="select Employee Photo"/>
            <asp:RequiredFieldValidator ID="rfvfuNewPhoto" runat="server" ErrorMessage="*" ToolTip="Select Photo"ControlToValidate="fuNewPhoto"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revfuNewPhoto" runat="server" Text="*" ToolTip="Image formate only"ControlToValidate="fuNewPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Operation</HeaderTemplate>
            <ItemTemplate>
            <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" />
            <asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" CausesValidation="true"OnClientClick="return confirm('Are you sure?')" />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" />
            <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
            </EditItemTemplate>

            <FooterTemplate>
            <asp:Button ID="btnNewInsert" runat="server" Text="Insert" OnClick="InsertNewRecord"/>
            <asp:Button ID="btnNewCancel" runat="server" Text="Cancel" OnClick="AddNewCancel" CausesValidation="false"/>
            </FooterTemplate>        
            </asp:TemplateField>           
            </Columns>
            <EmptyDataTemplate>
                      No record available                    
            </EmptyDataTemplate>       
        </asp:GridView>
        <br />
        <asp:Button ID="btnAdd" runat="server" Text="Add New Record" OnClick="AddNewRecord" />  
    </div>

Step 4:- Create one class within App_Code folderHere I have given this class named is GlobalClass and write following line of code.
using System.Data;
using System.Data.SqlClient;

public class GlobalClass
{
    public static SqlDataAdapter adap;
    public static DataTable dt;
    // Stored image path before updating the record
    public static string imgEditPath;
}

Step 5:- Create one folder, named Images, where we have stored employees photos see in following image.
Insert, Delete, Update in GridView in ASP.Net using C#
Step 6:- Write down following line of code in “.cs” page which related to your .aspx page (e.g. if your .aspx page name isdefault.aspx then your .cs file is default.aspx.cs).
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Call FillGridView Method
            FillGridView();
        }
    }
    /// <summary>
    /// Fill record into GridView
    /// </summary>
    public void FillGridView()
    {
        try
        {
            string cnString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
            SqlConnection con = new SqlConnection(cnString);
            GlobalClass.adap = new SqlDataAdapter("select * from gridview", con);
            SqlCommandBuilder bui = new SqlCommandBuilder(GlobalClass.adap);
            GlobalClass.dt = new DataTable();
            GlobalClass.adap.Fill(GlobalClass.dt);
            GridView1.DataSource = GlobalClass.dt;
            GridView1.DataBind();
        }
        catch
        {
            Response.Write("<script> alert('Connection String Error...') </script>");
        }
    }
    /// <summary>
    /// Edit record
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void editRecord(object sender, GridViewEditEventArgs e)
    {
        // Get the image path for remove old image after update record
        Image imgEditPhoto = GridView1.Rows[e.NewEditIndex].FindControl("imgPhoto"as Image;
        GlobalClass.imgEditPath = imgEditPhoto.ImageUrl;
        // Get the current row index for edit record
        GridView1.EditIndex = e.NewEditIndex;
        FillGridView();
    }

    /// <summary>
    /// Cancel the operation (e.g. edit)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        FillGridView();
    }

    /// <summary>
    /// Add new row into DataTable if no record found in Table
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AddNewRecord(object sender, EventArgs e)
    {
        try
        {
            if (GlobalClass.dt.Rows.Count > 0)
            {
                GridView1.EditIndex = -1;
                GridView1.ShowFooter = true;
                FillGridView();
            }
            else
            {
                GridView1.ShowFooter = true;
                DataRow dr = GlobalClass.dt.NewRow();
                dr["name"] = "0";
                dr["age"] = 0;
                dr["salary"] = 0;
                dr["country"] = "0";
                dr["city"] = "0";
                dr["photopath"] = "0";
                GlobalClass.dt.Rows.Add(dr);
                GridView1.DataSource = GlobalClass.dt;
                GridView1.DataBind();
                GridView1.Rows[0].Visible = false;
            }
        }
        catch
        {
            Response.Write("<script> alert('Row not added in DataTable...') </script>");
        }
    }

    /// <summary>
    /// Cancel new added record
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AddNewCancel(object sender, EventArgs e)
    {
        GridView1.ShowFooter = false;
        FillGridView();
    }

    /// <summary>
    /// Insert New Record
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void InsertNewRecord(object sender, EventArgs e)
    {
        try
        {
            string strName = GlobalClass.dt.Rows[0]["name"].ToString();
            if (strName == "0")
            {
                GlobalClass.dt.Rows[0].Delete();
                GlobalClass.adap.Update(GlobalClass.dt);
            }
            TextBox txtName = GridView1.FooterRow.FindControl("txtNewName"as TextBox;
            TextBox txtAge = GridView1.FooterRow.FindControl("txtNewAge"as TextBox;
            TextBox txtSalary = GridView1.FooterRow.FindControl("txtNewSalary"as TextBox;
            TextBox txtCountry = GridView1.FooterRow.FindControl("txtNewCountry"as TextBox;
            TextBox txtCity = GridView1.FooterRow.FindControl("txtNewCity"as TextBox;
            FileUpload fuPhoto = GridView1.FooterRow.FindControl("fuNewPhoto"as FileUpload;
            Guid FileName = Guid.NewGuid();
            fuPhoto.SaveAs(Server.MapPath("~/Images/" + FileName + ".png"));
            DataRow dr = GlobalClass.dt.NewRow();
            dr["name"] = txtName.Text.Trim();
            dr["age"] = txtAge.Text.Trim();
            dr["salary"] = txtSalary.Text.Trim();
            dr["country"] = txtCountry.Text.Trim();
            dr["city"] = txtCity.Text.Trim();
            dr["photopath"] = "~/Images/" + FileName + ".png";
            GlobalClass.dt.Rows.Add(dr);
            GlobalClass.adap.Update(GlobalClass.dt);
            GridView1.ShowFooter = false;
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Record not added...') </script>");
        }

    }
    /// <summary>
    /// Update the record
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void updateRecord(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            TextBox txtName = GridView1.Rows[e.RowIndex].FindControl("txtName"as TextBox;
            TextBox txtAge = GridView1.Rows[e.RowIndex].FindControl("txtAge"as TextBox;
            TextBox txtSalary = GridView1.Rows[e.RowIndex].FindControl("txtSalary"as TextBox;
            TextBox txtCountry = GridView1.Rows[e.RowIndex].FindControl("txtCountry"as TextBox;
            TextBox txtCity = GridView1.Rows[e.RowIndex].FindControl("txtCity"as TextBox;
            FileUpload fuPhoto = GridView1.Rows[e.RowIndex].FindControl("fuPhoto"as FileUpload;
            Guid FileName = Guid.NewGuid();
            if (fuPhoto.FileName != "")
            {
                fuPhoto.SaveAs(Server.MapPath("~/Images/" + FileName + ".png"));
                GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["photopath"] = "~/Images/" + FileName + ".png";
                File.Delete(Server.MapPath(GlobalClass.imgEditPath));
            }
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["name"] = txtName.Text.Trim();
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["age"] = Convert.ToInt32(txtAge.Text.Trim());
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["salary"] = Convert.ToInt32(txtSalary.Text.Trim());
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["country"] = txtCountry.Text.Trim();
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["city"] = txtCity.Text.Trim();
            GlobalClass.adap.Update(GlobalClass.dt);   
            GridView1.EditIndex = -1;
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Record updation fail...') </script>");
        }
    }

    /// <summary>
    /// Delete Record
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();
            GlobalClass.adap.Update(GlobalClass.dt);
            // Get the image path for removing deleted's record image from server folder
            Image imgPhoto = GridView1.Rows[e.RowIndex].FindControl("imgPhoto"as Image;
            File.Delete(Server.MapPath(imgPhoto.ImageUrl));
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Record not deleted...') </script>");
        }
    }
}

Step 7:- Now, save and build you application and execute. Your application output display as following.
Insert, Delete, Update in GridView in ASP.Net using C#
It’s your application first screen. Because there is not data in table so it displace message “No record available”.
Step 8:- For inserting data, click on button “Add New Record”. Now fill the data. Every controls have validation for prohibited wrong input.  
Insert, Delete, Update in GridView in ASP.Net using C#
After filling data, your GridView looking as following.  Here I have inserted three records.
Insert, Delete, Update in GridView in ASP.Net using C#
Note: - Id are generated automatic for every new record.
Step 9:- For updating records click button “Edit” and change TextBox Data and you can select new photo of employee. For example in place of age “28”, updated with “30” and in place of salary “50000”, updated with “55000”, then click button“Update”. Through button “Cancel” youreturn previous stage.
Insert, Delete, Update in GridView in ASP.Net using C#
Step 10:- For record deletion, click on button “Delete”. Before deleting record, confirmation alert message are popup. Here I have deleted 3rd record (e.g. Andrew Deniel). After deleting record your GridView looks as following.
Insert, Delete, Update in GridView in ASP.Net using C#