Step By Step Select, Insert, Update and Delete using ASP.NET C# and ADO.NET

 

Insert, Select, Update and Delete Statements

Insert, Select, Update and Delete statements these are basics of a programming because these are common coding practice which applies in development of application or a website associated with the database. Insert, Select, Update and Delete altogether also known as DML (Data Manipulation Language) statements which helps in managing the data with the database within schema objects.

What is a Database?

We will not get into more detailed explanation about the database but just a breif for undertsanding.

Database is a collection of data stored in a computer disc space or server space. In simple words it is a space where your data is been stored.

In a single database we can create any number of data tables. It's like a school with many classrooms and each classroom will have different school students.

In a single data table we create any number of columns For eg. studentID, studentName, studentAddress and in a single data table we can store data for specific topic.

Like to store student's records you can have students data table, For school accounts you can have accounts data table, For school results you can have results data table.

There are commonly used databases in our IT Zone

SQL - Microsoft SQL Server

Oracle - Oracle RDBMS or simply as Oracle

MYSQL - Open Source Freeware

MSACESS - Microsoft Access

PostgreSQL - ORDBMS

SAP - To manage customer relationship and other business operations

FoxPro - Database

IBM DB2 - IBM Database by IBM

Now in further we will try to understand about data manipulation statements i.e. (Insert, Select, Update and Delete).

About Data Manipulation Statements

Select Statement

Select statement let you to retrieve the data from the database table.

For ex :  In simple words if you want to pick up single student record, multiple student records or all students records from the table database you just need to use "Select" statement.

Example

 
Select * from 'students'

"*" - Means All

"students" - Data Table in a database.

Insert Statement

Insert statement lets you to insert new record or new data into the database table.

For ex :  In simple words if you want to add new student record then you need to use "Insert" Statement.

Example

 
Insert into student (studentID, studentName, studentAddress) values (1, "Khadak Singh", "Mulund - Mumbai");

"studentID, studentName, studentAddress" - Column Names inside student table

"student” - Table in a database.

Note: For numeric data we dont use (" ") inverted comma and for string data we use (" ") inverted comma .

Update Statement

Update Statement lets you to update existing one or more records in the database table depending on condition.

For ex:  Updating existing student records.

Example

 
Update student set studentID=2, studentName = "Khadak Sharma", studentAddress = "Parel" Where studentID = 1;

"Where studentID = 1 " - It is a condition, means update student record whose ID number is = 1.

Delete Statement

Delete statement helps to delete one or more records from the database table depending on condition.

For ex: Removing any student from a class.

Example

 
Delete From student Where studentID = 1;

"Where studentID = 1 " - It is a condition, means delete student record whose ID number is = 1.

Why Insert, Select, Update and Delete

When we have a website or an application associated with database (Sql, Oracle, Mysql and so on) then to do manipulation (i.e. Displaying, Deletion, Updating and Insertion) in the database we have to use only DML Language statements (i.e. Insert, Select, Update and Delete Statements).

Now that you have understoond about data manipulation language, now let's do step by step insert, update, delete and select using asp.net c# code with ado.net objects.

Step By Step Select, Insert Update and Delete

To demonstrate step by step insert update delete and select, we will be using a simple web application, you can choose anything web or windows depending on your requirement the coding part will remain the same.

Step 1

Create a web forms application

Step 2:

Create a Database

After creating a new website, create a new database from server explorer of visual studio or SQL server. We have shown you an example through visual studio 2010.

After creating a new database, let's add new data tables with colums like as shown in below image file.

Note : To create tables just click on your database name go to tables folder, when you choose to create a table it will ask you add columns. You can add your custom name column names along with data type. (Data Type : For string data choose - varchar(50) or above, for integer data choose - int)

Step 3

Adding connection string to web.config file.

First Right click on the database name then click on the properties (Alt + Enter).

Find the connection string then copy that connection string

Once you have copied the connection string go to your asp.net web site solution explorer. Find the web.config file open that web.config file.

Replace the above connection string with your copied connection string.

Step 4

Add new aspx file i.e. default.aspx file to your web project.

Then

Drag and drop a gridview to the page from the tool box then do the following as shown in below.

i.e. Add - Edit Delete buttons from the command field and check on the auto generate fields. Edit link is for to choose which record to edit and delete link is for to delete the selected record.

Create a form to update and insert records into database from website as shown above i.e. Name, Address and Salary then add one hidden field and two submit buttons, name it.

Step 5

Displaying records using select statement

We will be display the records on grid view. So let’s display the records using select statement.

Open Up Connection to Database

First thing we need to open up a connection to a database. So let’s do that step by step

In default.aspx.cs file import the SQL namespaces on top .

 
using System.Data
using System.Data.SqlClient;

Now in a page load write the connection string and open up the sql connection as shown below.

 
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();

Displaying records on to grid view

After opening up the sql connection, Let's write the Select statement in the sql command and the execute the sql query using sql command execute reader and append it to grid view data source as shown below.

 
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Select * from Employee", objsqlconn);
grd_dataset.DataSource = objcmd.ExecuteReader();
grd_dataset.DataBind();

Output

Step 6

Inserting a new record using Insert Statement

To add new record to the database we will use the following form that we have created in our default.aspx file.

We will write insert statement in the button click event. So double click on a button, a button click event opens up.

First we need to open up the sql connection as same as previously we did it for select statement then in a sql command write the following insert statement as shown below.

 
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Insert into Employee(Employee_Name,Employee_Address,Employee_Salary) Values('" + txtName.Text + "','" + txtAddress.Text + "','" + txtSal.Text + "')", objsqlconn);
objcmd.ExecuteNonQuery();

Then by using the command object call the ExecuteNonQuery() method to execute query. We normally use this method while updating, deleting and inserting.

txtName.Text, txtAddress.Text and txtSal.Text are the form input name to take form input data.

So just run the website by holding Ctrl + F5 and add input data in the text box finally click on add new record button to add new record to the database.

Step 7

Updating an existing record using update statement

What we did here, we have displayed the records in the grid view screen and there itself we have provided an option for edit and delete as a link as shown below.

When a user clicks on an edit link of any selected row of data then "select" query or statement fires and it display’s the records in the following form as shown below.

So for now we will assume that user clicks on the edit link and following details displayed on the screen as shown below.

So we have just clicked on 10th record and the same data appears on the screen and we have recorded the employee ID i.e. Number = 10 in our hiddenfield. If you see our form there we have a hiddenfield of employee ID.

HiddenFields: It helps us to store the important values which we can use it in the later part of coding.

This hidden field value or employee ID, I'm going to use it in an update statement for an updating purpose.

So next step when a user clicks on update button on the form, we have to fire an update statement, so fire an update statement.

 
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Update Employee set Employee_Name='" + txtName.Text + "',Employee_Address='" + txtAddress.Text + "',Employee_Salary='" + txtSal.Text + "' where Employee_Id='" + txtEmpID.Value + "'", objsqlconn);

objcmd.ExecuteNonQuery();

Procedure is same, first we need to open up sql connection, then on sql command we to just need to write an update statement with the "Where" condition.

Note: In our "WHERE" condition we have passed hidden field value to employee id.

Step 8

Deleting an existing record using delete statement

What we did here, we have displayed all the records in the grid view screen and there itself for each record we have provided an option for edit and delete as a link as shown below.

 

So when a user clicks on the delete link of selected row, on delete link event args we have fired delete statement with following delete code as shown below.

 
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Delete from Employee Where Employee_ID='" + _empID + "'", objsqlconn);
objcmd.ExecuteNonQuery();
 
protected void grd_dataset_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = Convert.ToInt32(e.RowIndex);
        int _empID = 0;

        _empID = Convert.ToInt16(grd_dataset.Rows[index].Cells[2].Text);
        if (_empID != 0)
        {

            string conn = "";
           
            conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
            SqlConnection objsqlconn = new SqlConnection(conn);
            try
            {

                    objsqlconn.Open();
                    SqlCommand objcmd = new SqlCommand("Delete from Employee Where Employee_ID='" + _empID + "'", objsqlconn);
                    objcmd.ExecuteNonQuery();
                    ClearAll();
                    Response.Redirect("Default.aspx");
                



            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
            finally
            {
                objsqlconn.Close();
            }
          
        }
    }

Note : _empID - we got from the gridview columns 

Delete Procedure is same as did it for update and insert, first we need to open up sql connection, then on sql command we to just need to write a delete statement with the "Where" condition.

So my technical friend I hope that you have understood about insert, update, select and delete using asp.net c# and ado.net class object. If you have any doubts regarding this topic you can add your valuable comments. If you like this article kindly share it with your friends. Happy Coding

 

 

:: SHARE THIS POST ::

        
 

More DOT.NET Articles To Read Next:

 
Apr
18
2013

Roles of Common Language Runtime in Dot.Net Framework

CLICK TO READ FULL ARTICLE

Views - 37400 |Category - DOT.NET

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

h8td3

 

 
Comments

Posted by Nyan Win Luck on 2016-04-28

I've some error! Asp.net runtime error! Only content control are allowed directly in a contrnt page that contains content controls! This error I'm writing sqldatasource to appear dropdownlist

Posted by Nawab on 2016-02-25

i am looking for a event handling.

Posted by Desai chandni on 2015-08-26

very help full & simple to a explain

Posted by RAGAVAN on 2015-08-19

very useful

Posted by Rahul on 2015-08-18

owesum teaching keep going u r bestway explaination

Posted by Safuvan on 2015-08-17

tanx alot....its so helpful....easy nd simple

Posted by Waqas khan on 2015-02-21

Thank you brother its very helpful....

Posted by Sagar on 2015-02-13

thanks....

Posted by Naqi Zaidi on 2015-01-26

how to connnection with Step By Step Select, Insert, Update and Delete using ASP.NET C# with Microsoft SQL Server

Posted by Navid on 2015-01-14

Nice article, plz provide Oracle 9i and ASP.net 2012 ADD EDIT DELETE application sample too

Posted by Rudra on 2015-01-13

This article is really useful to me..thanks for showing it step by step which is easy to understand..can you help me for insert update and deleting only images from database with validation.????(no limit on size of image)

Posted by Rudra on 2015-01-13

This article is really useful to me..thanks for showing it step by step which is easy to understand..can you help me for insert update and deleting only images from database with validation.????(no limit on size of image)

Posted by Dataset does not exist in current context on 2015-01-01

please help me out and send me the solution i have am performing this project but it shows error on dataset. help me asap grd_dataset.DataSource

Posted by Vidyashree on 2014-12-27

i m new to asp.net give me solution CREATE DATABASE permission denied in database 'master'. Cannot attach the file 'C:\Documents and Settings\user\My Documents\ado.mdf' as database 'ado'.

Posted by Prajakta on 2014-12-22

It was of a great help..thanks..good article.

Posted by Sagar on 2014-12-10

great job dude helped a lot

Posted by Sanket on 2014-11-30

Thanks it is very usefull for me

Posted by Aditi Patel on 2014-11-26

Such a helpful info using very easy and understandable language. Really very nice. Thanks.

Posted by Rahul on 2014-10-20

Thanxxxxx............

Posted by MANOJ Kashyap on 2014-10-19

hello nice

Posted by Hetvy on 2014-10-15

This is very useful for me thank u but plz say how 2 create db in SQL with query & how 2 fetch any single record on output with query. Plz reply me.thank you

Posted by Swathy mohanan on 2014-10-09

good

Posted by Nikhhil on 2014-09-29

hello nice

Posted by Andy Weil on 2014-09-25

The article you submitted are really very useful for and i want to step by step article like How to create Trigger and many more. So, i request to you please provide that type information and is it possible to find your article in a pdf form.

Posted by Jayaprasad on 2014-09-19

thank u

Posted by Kaushik on 2014-09-08

than x lots

Posted by Narasingh on 2014-09-04

sir,,,u really superbb,,,i m beginner...this article very nice ,,,,plss,,,give more article...and pls write for beginners for easy undstndng

Posted by Alok on 2014-08-22

nic .....

Posted by Keshawa on 2014-08-17

Very much Helpful. Can you please describe the code of clicking "Edit".

Posted by Jayesh Kotadiya on 2014-08-08

How to Set HiddenFiled and selected index change row cell???

Posted by Viral Khunt on 2014-08-03

Thanks lot of... U help me??? my project Mycollege ERP system Software

Posted by Sachin Kumar on 2014-07-20

Please hep me to store bulk excel data in database in asp.net using c#, And please let me know how to make connection to store excel data in database

Posted by Sethsaren on 2014-07-20

thank

Posted by Nuux ali ibraahim on 2014-07-03

so thankz for softerware engineer

Posted by Bs123 on 2014-06-26

thnks sir

Posted by Roshni pashine on 2014-06-25

nice coding.but plz can provide more specific details how to create forms

Posted by Srinivas on 2014-06-03

nice coding

Posted by Joanna on 2014-05-23

need update statement thank you

Posted by Jaydeep on 2014-05-20

thank brother for coding insert update and deleting

Posted by Nasemaeeb on 2014-05-14

i want update controls

Posted by Vijay goyal on 2014-05-12

Thanks for providing a good tutorials. Sir Please give me some information about Ado.net like Execute Non Query, sqlDatareader ,Data set and so on.

Posted by Admin on 2014-04-23

For mysql connections check this my new article Mysql Connection CLick Here http://www.onlinebuff.com/article_step-by-step-to-upload-an-image-and-store-in-database-using-php_40.html

Posted by Admin on 2014-04-23

Hi #D.ANBARASAN, Please check the code i have re-written the delete. I have written delete code in grid view row deletion click event. Thank you for your comments

Posted by D.ANBARASAN on 2014-04-17

where i'll write the delete coding,i can't understand...plz ans this question...

Posted by D.ANBARASAN on 2014-04-17

where i'll write the delete coding,i can't understand...plz ans this question...

Posted by Monil Thakor on 2014-04-02

Than Q nyc article bro.

Posted by Nitin on 2014-03-28

Very nice code .....

Posted by Amit Gupta on 2014-03-27

Plz send me how to make gridview in database.

Posted by Sathya on 2014-03-25

It's very useful for me. But i need mysql connection codings

Posted by EmiJames on 2013-11-27

where i'll write the delete coding,i can't understand...plz ans this question...

Posted by Pranav on 2013-11-26

how to insert database

Posted by Pramod on 2013-10-16

very nice & its a very helpful for anyone... Thanking you...

Posted by Mohammed on 2013-10-04

ya.simple and super

Posted by Porknbeans on 2013-10-03

what is grd_dataset?

Posted by Vagat singh on 2013-09-29

Very very best site for understanding the basic concepts with example.