CRUD Operations Using ASP.Net ListView

This is all about operations on SQL tables using Stored Procedures, so I will explain step-by-step how to insert, select, edit and delete operations with a ListView control.

Step 1

In a SQL Database first create a table in a database store to insert a data value into a table as follows.

Create Table EmployeeData.

  1. Create Table EmployeeData  
  2. (  
  3.    EmpID int identity (1,1) Primary Key,  
  4.    EmpName varchar(30),  
  5.    Contact nchar(15),  
  6.    EmailId nvarchar(50)  
  7. )  
In this new table the EmpID column is an auto-increment defined for Employee Identity.

Step 2

In Visual Studio create a UI design using the following procedure:
  • Go to Solution Explorer.
  • Right-click on the project and click the Add tab.
  • Click the Add New Item as in the following:

Add Web Form
Figure 1: Add Web Form

Now I will write the design code inside ListView.aspx. In this page add some TextBox controls, Buttons and a ListView Control.

First create a TextBox Control, Button Control, ListView Control and hidden field control. First add the TextBox control for the data to be filled on the UI page.

Also add the ListView control for the Bind Employee record from the SQL Database and display it in the ListView Control. Also add two button controls inside the ListView control for the ListView data row delete and edit. The following is the UI design code.

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Master/Master.master" AutoEventWireup="true" CodeFile="ListView.aspx.cs" Inherits="UI_ListView" %>  
  2.   
  3. <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">  
  4. </asp:Content>  
  5. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >  
  6.   
  7.      <div>  
  8.         <fieldset style="width: 300px"><legend>ListView Example</legend>  
  9.         <asp:Table runat="server" >  
  10.             <asp:TableRow>  
  11.                 <asp:TableCell>Name</asp:TableCell><asp:TableCell><asp:TextBox runat="server" ID="txtName"></asp:TextBox></asp:TableCell>  
  12.             </asp:TableRow>  
  13.             <asp:TableRow>  
  14.                 <asp:TableCell>Contact</asp:TableCell><asp:TableCell><asp:TextBox runat="server" ID="txtContact"></asp:TextBox></asp:TableCell>  
  15.             </asp:TableRow>  
  16.             <asp:TableRow>  
  17.                 <asp:TableCell>Email</asp:TableCell><asp:TableCell><asp:TextBox runat="server" ID="txtEmail"></asp:TextBox></asp:TableCell>  
  18.             </asp:TableRow>  
  19.            <asp:TableRow>  
  20.                <asp:TableCell></asp:TableCell>  
  21.                <asp:TableCell>   
  22.                    <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />  
  23.                    <asp:Button runat="server" ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click" />  
  24.                </asp:TableCell>  
  25.        </asp:TableRow>  
  26.       </asp:Table>  
  27.        </fieldset>  
  28.          </div>  
  29.   
  30.        <asp:HiddenField ID="hfRecord" runat="server" />  
  31.   
  32. <h3>Employee Information</h3>  
  33.   
  34.         <asp:ListView ID="ListEmployee" runat="server" OnItemCommand="ListEmployee_ItemCommand" DataKeyNames="EmpID" >  
  35.         <itemtemplate>  
  36.        <table >  
  37.            <tr>  
  38.                         <td style =" width : 100px">  
  39.                             <b>No. :</b>  
  40.                             <%#Eval("EmpID") %>  
  41.                         </td>  
  42.                         <td style =" width : 200px">  
  43.                             <b>Name :</b>  
  44.                             <%#Eval("EmpName") %>  
  45.                         </td>  
  46.                         <td style =" width : 200px">  
  47.                             <b>Contact :</b>  
  48.                             <%#Eval("Contact") %>  
  49.                         </td >  
  50.                         <td style =" width : 250px">  
  51.                             <b>Email :</b>  
  52.                             <%#Eval("EmailId") %>  
  53.                         </td>  
  54.                     <td>  
  55.                         <asp:Button ID="btndel" runat="server" Text="Delete" tooltip="Delete a record" onclientclick="javascript:return confirm('Are you sure to delete record?')" CommandName="EmpDelete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmpID") %>' />  
  56.                         <asp:Button ID="btnupdt" runat="server" Text="Edit" tooltip="Update a record" CommandName="EmpEdit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmpID") %>' />  
  57.                     </td>  
  58.             </tr>  
  59.        </table>  
  60.        </itemtemplate>  
  61.     </asp:ListView>  
  62. </asp:Content>  
Step 3

In the database, again go to the SQL Server and create an Insert procedure, a Delete procedure, a Select procedure and an Update procedure as in the following.

 

  1. Select procedure for ListView control
    1. create procedure sp_FillData  
    2. As  
    3.    Begin  
    4.    set nocount on;  
    5.    select EmpID, EmpName, Contact, EmailID from EmployeeData  
    6. End  
  2. Insert procedure
    1. create procedure sp_InsertEmployeeData  
    2.    @EmpName varchar(30),  
    3.    @Contact nchar(15),  
    4.    @EmailId nvarchar(50)  
    5. As  
    6.    Begin  
    7.    set nocount on;  
    8.    Insert into dbo.EmployeeData   
    9.       (EmpName,Contact,EmailId)  
    10.    values  
    11.       (@EmpName,@Contact,@EmailId)  
    12. End   
  3. Delete procedure
    1. Create procedure sp_DeleteEmployeeData  
    2.    @EmpID int  
    3. As  
    4.    Begin  
    5.    set nocount on;  
    6.    Delete from EmployeeData where EmpID=@EmpID  
    7. End  
  4. Select procedure
    1. create procedure sp_SelectEmployeeData  
    2.    @EmpID int  
    3. As  
    4.    Begin  
    5.    set nocount on;  
    6.    select EmpID, EmpName, Contact, EmailID from EmployeeData where EmpID=@EmpID  
    7. End  
  5. Update procedure
    1. Create procedure sp_UpdateEmployeeData  
    2.    @EmpID int,  
    3.    @EmpName varchar(30),  
    4.    @Contact nchar(15),  
    5.    @EmailId nvarchar(50)  
    6. As  
    7.    Begin  
    8.    set nocount off;  
    9.    UPDATE Employeedata SET EmpName=@EmpName,Contact=@Contact,EmailId=@EmailId WHERE EmpID=@EmpID  
    10. End  

Step 4

Inside the project's Web.Config, provide the database connection string as in the following:

  1. <connectionStrings>  
  2.    <add name="connstr" connectionString="Data Source=RAKESH-PC;Initial Catalog=SqlServerTech;User ID=sa;Password=password" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Step 5

Now go to the UI code side section. In this first write code for the TextBox value insertion in the SQL table by the preceding Insert Procedure, then write code for the inserted record display in the ListView control. Write the code for two buttons, one the delete and the second is an edit button code. Write it for the data delete and update in the database records. Both code writes an Itemcommand on the ListView Control. An Itemcommand is created as in the following figure:

Add an Item Command
Figure 2: Add an Item Command

Create two action commands, an EmpEdit for a record update and an EmpDelete for a record delete, inside the ItemCommand Event.

This is a UI back side code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10.   
  11. public partial class UI_ListView : System.Web.UI.Page  
  12. {  
  13.     string connection = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;  
  14.     protected void Page_Load(object sender, EventArgs e)  
  15.     {  
  16.         if (!IsPostBack)  
  17.         {  
  18.             GetEmployeeDetail();  
  19.         }  
  20.     }  
  21.     void GetEmployeeDetail()  
  22.     {  
  23.         SqlConnection con = new SqlConnection(connection);  
  24.   
  25.         SqlCommand cmd = new SqlCommand("sp_FillData", con);  
  26.         cmd.CommandType = CommandType.StoredProcedure;  
  27.   
  28.         con.Open();  
  29.         ListEmployee.DataSource = cmd.ExecuteReader();  
  30.         ListEmployee.DataBind();  
  31.     }  
  32.     protected void btnSave_Click(object sender, EventArgs e)  
  33.     {  
  34.         using (SqlConnection con = new SqlConnection(connection))  
  35.         {  
  36.             using (SqlCommand cmd = new SqlCommand("sp_InsertEmployeeData", con))  
  37.             {  
  38.                 cmd.CommandType = CommandType.StoredProcedure;  
  39.                 con.Open();  
  40.                 cmd.Parameters.AddWithValue("@EmpName", SqlDbType.VarChar).Value = txtName.Text.Trim();  
  41.                 cmd.Parameters.AddWithValue("@Contact", SqlDbType.NChar).Value = txtContact.Text.Trim();  
  42.                 cmd.Parameters.AddWithValue("@EmailId", SqlDbType.NVarChar).Value = txtEmail.Text.Trim();  
  43.                 cmd.ExecuteNonQuery();  
  44.                 con.Close();  
  45.   
  46.                 txtName.Text = String.Empty;  
  47.                 txtContact.Text = String.Empty;  
  48.                 txtEmail.Text = String.Empty;  
  49.             }  
  50.         }  
  51.         GetEmployeeDetail();  
  52.     }  
  53.     protected void btnUpdate_Click(object sender, EventArgs e)  
  54.     {  
  55.         SqlConnection con = new SqlConnection(connection);  
  56.         SqlCommand cmd = new SqlCommand("sp_UpdateEmployeeData", con);  
  57.         cmd.CommandType = CommandType.StoredProcedure;  
  58.   
  59.         cmd.Parameters.AddWithValue("@EmpID", Convert.ToInt32(hfRecord.Value));  
  60.         cmd.Parameters.AddWithValue("@EmpName", SqlDbType.VarChar).Value = txtName.Text.Trim();  
  61.         cmd.Parameters.AddWithValue("@Contact", SqlDbType.NChar).Value = txtContact.Text.Trim();  
  62.         cmd.Parameters.AddWithValue("@EmailId", SqlDbType.NVarChar).Value = txtEmail.Text.Trim();  
  63.   
  64.         con.Open();  
  65.         cmd.ExecuteNonQuery();  
  66.         con.Close();  
  67.   
  68.         GetEmployeeDetail();  
  69.   
  70.         btnSave.Visible = true;  
  71.         btnUpdate.Visible = false;  
  72.   
  73.         hfRecord.Value = string.Empty;  
  74.         txtName.Text = String.Empty;  
  75.         txtContact.Text = String.Empty;  
  76.         txtEmail.Text = String.Empty;  
  77.     }  
  78.     protected void ListEmployee_ItemCommand(object sender, ListViewCommandEventArgs e)  
  79.     {  
  80.         switch (e.CommandName)  
  81.         {  
  82.             case ("EmpDelete"):  
  83.                 int EmpID = Convert.ToInt32(e.CommandArgument);  
  84.                 deleteEmployee(EmpID);  
  85.                 break;  
  86.             case ("EmpEdit"):  
  87.                 EmpID = Convert.ToInt32(e.CommandArgument);  
  88.                 UpdateEmployeeDetail(EmpID);  
  89.                 break;  
  90.         }  
  91.     }  
  92.    void deleteEmployee(int EmpID)  
  93.     {  
  94.         SqlConnection con = new SqlConnection(connection);  
  95.         SqlCommand cmd = new SqlCommand("sp_DeleteEmployeeData", con);  
  96.         cmd.CommandType = CommandType.StoredProcedure;  
  97.   
  98.         cmd.Parameters.AddWithValue("@EmpID", EmpID);  
  99.         con.Open();  
  100.         cmd.ExecuteNonQuery();  
  101.         con.Close();  
  102.         GetEmployeeDetail();  
  103.    }  
  104.     void UpdateEmployeeDetail(int EmpID)  
  105.     {  
  106.         SqlConnection con = new SqlConnection(connection);  
  107.         SqlCommand cmd = new SqlCommand("sp_SelectEmployeeData", con);  
  108.         cmd.CommandType = CommandType.StoredProcedure;  
  109.         cmd.Parameters.AddWithValue("@EmpID", EmpID);  
  110.   
  111.         con.Open();  
  112.         SqlDataReader dr = cmd.ExecuteReader();  
  113.         if (dr.HasRows)  
  114.         {  
  115.             dr.Read();  
  116.             hfRecord.Value = dr["EmpID"].ToString();  
  117.             txtName.Text = dr["EmpName"].ToString();  
  118.             txtContact.Text = dr["Contact"].ToString();  
  119.             txtEmail.Text = dr["EmailId"].ToString();  
  120.         }  
  121.         dr.Dispose();  
  122.   
  123.         con.Close();  
  124.         btnSave.Visible = false;  
  125.         btnUpdate.Visible = true;  
  126.         GetEmployeeDetail();  
  127.     }  
  128.   
  129. }  
Step 6

For the browser side, run your new page in the web browser.

Fill Record and Save
Figure 3: Fill Record and Save

Press the Save button and save the data into the table and the inserted record is displayed in the browser using the ListView control as in the following.

Display Inserted Record
Figure 4: Display Inserted Record

Check in Database
Figure 5: Check in Database

Now delete record number 68 by deleting the button.

Record Delete Massage
Figure 6: Record Delete Message

Now you will see that the deleted record is not available in the database and not displayed on the page.

Now Update Record Process Record Number 66. In this change the Emailid.

Record Update
Figure 7: Record Update

And also check in the data table.

Record Update and Delete in SQL
Figure 8: Record Update and Delete in SQL

As you can see, inside the database, the deleted record is not there and the Employee Emailid is updated.

I hope you understood how to work with the ListView control and SQL Procedures.

Have a nice day.

Up Next
    Ebook Download
    View all
    Learn
    View all