List View Control With CRUD And Search Record

ASP.NET Web Form is still used by a large number of developers for rapid application development. This tutorial is a CRUD (Create, Retrieve, Update, and Delete) Web Application with the "search for a record" functionality. The records are displayed in a ListView Control which involves model binding. Data Pager is used for pagination of the records.

The data-bound controls (such as the ListView, the Repeater, the GridView, the DetailsView, and the FormView) are Strongly-Typed Data-Bound Controls.

Note - Required Libraries are deleted from the bin folder of the uploaded project as the file size became bigger than upload limit 10 MB.

Software required for this tutorial is -

  1. Microsoft .NET Framework 4.5.1or any higher version.
  2. Microsoft Visual Studio 2013 or Visual Studio Express 2013 for Web or any higher version of Microsoft Visual Studio above 2012
  3. Entity Framework 6.0

Lunch Visual Studio and create a new ASP.NET project. Name it as List View Search.

Go to File >> New Project.

List View Control With CRUD And Search Record 

The project looks like below.

List View Control With CRUD And Search Record 

Default.aspx Page

  1. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ListViewSearch._Default" %>  
  2. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  3.     <h1> Employee Manager</h1>  
  4.     <div>  
  5.         <asp:TextBox ID="txtSearch" AutoPostBack="true" runat="server" ToolTip="Search by part of EmployeeName"></asp:TextBox>  
  6.         <asp:Button ID="btnSearch" Text="Search" runat="server" CausesValidation="false" OnClick="btnSearch_Click" />  
  7.     </div>  
  8.     <div>  
  9.         <asp:ListView ID="EmployeeList" ItemType="ListViewSearch.Models.Employee" SelectMethod="GetSearchedItems" DataKeyNames="Id" UpdateMethod="UpdateEmployee" DeleteMethod="DeleteEmployee" OnSelectedIndexChanged="EmployeeList_SelectedIndexChanged" runat="server">  
  10.             <EmptyDataTemplate>  
  11.                 <table>  
  12.                     <tr>  
  13.                         <td>Sorry,No Record Found.Try Again!</td>  
  14.                     </tr>  
  15.                 </table>  
  16.             </EmptyDataTemplate>  
  17.             <EmptyItemTemplate>  
  18.                 <td />  
  19.             </EmptyItemTemplate>  
  20.             <LayoutTemplate>  
  21.                 <div class="outerContainer">  
  22.                     <table id="EmployeeTable">  
  23.                         <caption style="color:deeppink"><b>Employees</b></caption>  
  24.                         <tr style="background-color:crimson">  
  25.                             <th>EmpId</th>  
  26.                             <th>FirstNam</th>  
  27.                             <th>LastName</th>  
  28.                             <th>Salary</th>  
  29.                             <th>ContactNo</th>  
  30.                             <th>DateOfBirth</th>  
  31.                             <th style="width:140px;">      Action</th>  
  32.                         </tr>  
  33.                         <tr runat="server" id="itemPlaceholder"></tr>  
  34.                     </table>  
  35.                 </div>  
  36.             </LayoutTemplate>  
  37.             <ItemTemplate>  
  38.                 <tr>  
  39.                     <td>  
  40.                         <%# Item.Id %>  
  41.                     </td>  
  42.                     <td>  
  43.                         <%# Item.FirstName %>  
  44.                     </td>  
  45.                     <td>  
  46.                         <%# Item.LastName %>  
  47.                     </td>  
  48.                     <td>  
  49.                         <%# Item.Salary %>  
  50.                     </td>  
  51.                     <td>  
  52.                         <%# Item.ContactNo %>  
  53.                     </td>  
  54.                     <td>  
  55.                         <%# Item.Date_Of_Birth %>  
  56.                     </td>  
  57.                     <td>  
  58.                         <asp:Button BackColor="#ff3399" CommandName="Edit" Text="Edit" tooltip="Edit a record" CausesValidation="false" runat="server" />  
  59.                         <asp:Button BackColor="#ff3399" CommandName="Delete" tooltip="Delete a record" CausesValidation="false" onclientclick="javascript:return confirm('Are you sure to delete record?')" Text="Delete" runat="server" />  
  60.                     </td>  
  61.                 </tr>  
  62.             </ItemTemplate>  
  63.             <EditItemTemplate>  
  64.                 <tr>  
  65.                     <input type="hidden" name="EmpId" value="<%# Item.Id %>" />  
  66.                     <td>EmpId:  
  67.                         <asp:TextBox ID="txtEmpId" runat="server" TextMode="SingleLine" Text='<%# BindItem.Id%>' />  
  68.                     </td>  
  69.                     <td>FirstName:  
  70.                         <asp:TextBox ID="txtFName" runat="server" TextMode="SingleLine" Text='<%# BindItem.FirstName %>' />  
  71.                     </td>  
  72.                     <td>LastName:  
  73.                         <asp:TextBox ID="txtLName" runat="server" TextMode="SingleLine" Text='<%# BindItem.LastName %>' />  
  74.                     </td>  
  75.                     <td>Salary:  
  76.                         <asp:TextBox ID="txtSalary" runat="server" TextMode="SingleLine" Text='<%# BindItem.Salary %>' />  
  77.                     </td>  
  78.                     <td>ContactNo:  
  79.                         <asp:TextBox ID="txtContactNo" runat="server" TextMode="SingleLine" Text='<%# BindItem.ContactNo %>' />  
  80.                     </td>  
  81.                     <td>Date of Birth:  
  82.                         <asp:TextBox ID="txtDOB" runat="server" TextMode="SingleLine" Text='<%# BindItem.Date_Of_Birth %>' />  
  83.                     </td>  
  84.                     <td>  
  85.                         <asp:Button BackColor="#ff0066" CommandName="Update" Text="Update" CausesValidation="false" runat="server" />  
  86.                         <asp:Button BackColor="#ff0066" CommandName="Cancel" Text="Cancel" CausesValidation="false" runat="server" />  
  87.                     </td>  
  88.                 </tr>  
  89.             </EditItemTemplate>  
  90.         </asp:ListView>  
  91.         <hr style="color:darkblue" />  
  92.         <div style="clear: both;">  
  93.             <asp:DataPager ID="DataPager1" PagedControlID="EmployeeList" PageSize="2" runat="server">  
  94.                 <Fields>  
  95.                     <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowPreviousPageButton="true" ShowNextPageButton="false" ShowLastPageButton="false" />  
  96.                     <asp:NumericPagerField ButtonType="Link" />  
  97.                     <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="true" ShowNextPageButton="true" ShowFirstPageButton="false" ShowPreviousPageButton="false" />  
  98.                 </Fields>  
  99.             </asp:DataPager>  
  100.         </div>  
  101.     </div>  
  102.     <hr style="width:5px;color:darkblue;" />  
  103.     <asp:Label ID="LabelStatus" BackColor="Blue" Width="540px" Height="5px" runat="server" Text=""></asp:Label>  
  104.     <h3>Add Employee:</h3>  
  105.     <table>  
  106.         <tr>  
  107.             <td>  
  108.                 <asp:Label ID="LabelAddId" runat="server">ID:</asp:Label>  
  109.             </td>  
  110.             <td>  
  111.                 <asp:TextBox ID="AddId" runat="server"></asp:TextBox>  
  112.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" Text="* Id required." ControlToValidate="AddId" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>  
  113.             </td>  
  114.         </tr>  
  115.         <tr>  
  116.             <td>  
  117.                 <asp:Label ID="LabelAddFName" runat="server">FirstName:</asp:Label>  
  118.             </td>  
  119.             <td>  
  120.                 <asp:TextBox ID="AddFirstName" runat="server"></asp:TextBox>  
  121.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="* First name required." ControlToValidate="AddFirstName" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>  
  122.             </td>  
  123.         </tr>  
  124.         <tr>  
  125.             <td>  
  126.                 <asp:Label ID="LabelAddLName" runat="server">LastName:</asp:Label>  
  127.             </td>  
  128.             <td>  
  129.                 <asp:TextBox ID="AddLastName" runat="server"></asp:TextBox>  
  130.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" Text="* Last name required." ControlToValidate="AddLastName" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>  
  131.             </td>  
  132.         </tr>  
  133.         <tr>  
  134.             <td>  
  135.                 <asp:Label ID="LabelAddSalary" runat="server">Salary:</asp:Label>  
  136.             </td>  
  137.             <td>  
  138.                 <asp:TextBox ID="AddSalary" runat="server"></asp:TextBox>  
  139.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Text="* Salary required." ControlToValidate="AddSalary" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>  
  140.             </td>  
  141.         </tr>  
  142.         <tr>  
  143.             <td>  
  144.                 <asp:Label ID="LabelAddContactNo" runat="server">ContactNo:</asp:Label>  
  145.             </td>  
  146.             <td>  
  147.                 <asp:TextBox ID="AddContactNo" runat="server"></asp:TextBox>  
  148.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Text="* ContactNo required." ControlToValidate="AddContactNo" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>  
  149.             </td>  
  150.         </tr>  
  151.         <tr>  
  152.             <td>  
  153.                 <asp:Label ID="LabelAddDOB" runat="server">Date Of Birth:</asp:Label>  
  154.             </td>  
  155.             <td>  
  156.                 <asp:TextBox ID="AddDOB" runat="server"></asp:TextBox>  
  157.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" Text="* Date of Birth required." ControlToValidate="AddDOB" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>  
  158.             </td>  
  159.         </tr>  
  160.     </table>  
  161.     <p></p>  
  162.     <p></p>  
  163.     <asp:Button ID="AddEmployeeButton" runat="server" Text="Add Employee" OnClick="AddEmployeeButton_Click" CausesValidation="true" />  
  164.     <p></p>  
  165. </asp:Content>  

Default.aspx.cs Page

  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 ListViewSearch.Models;  
  8. using System.Web.ModelBinding;  
  9.   
  10.   
  11. namespace ListViewSearch  
  12. {  
  13.     public partial class _Default : Page  
  14.     {  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.              
  18.   
  19.         }  
  20.   
  21.         TutorialEntities DBContext = new ListViewSearch.Models.TutorialEntities();       
  22.           
  23.   
  24.         /*public IQueryable GetEmployees()//This piece of code is used to populate the list view but not used here. 
  25.         { 
  26.             var _db = new ListViewSearch.Models.TutorialEntities(); 
  27.             IQueryable query = _db.Employees.OrderBy(emp => emp.Id); 
  28.             return query; 
  29.         }*/  
  30.   
  31.   
  32.         protected void btnSearch_Click(object sender, EventArgs e)  
  33.         {  
  34.             Response.Write("<script>Window.location.reload()</script>");  
  35.   
  36.         }  
  37.   
  38.         public IQueryable<Employee> GetSearchedItems([Control("txtSearch")]string Search)  
  39.         {  
  40.             //As there is no search word is given so listview is populated with all records sorted by First Name  
  41.             IQueryable<Employee> query = DBContext.Employees.OrderBy(emp => emp.FirstName);  
  42.   
  43.             if (!string.IsNullOrEmpty(Search))  
  44.             {  
  45.                 query = query.Where(emp => (emp.FirstName.Contains(Search) || emp.LastName.Contains(Search)));  
  46.   
  47.             }  
  48.             return query;  
  49.         }  
  50.   
  51.           
  52.         public void DeleteEmployee(int id)  
  53.         {                     
  54.             Employee oEmployee = DBContext.Employees.Find(id);  
  55.             DBContext.Employees.Remove(oEmployee);  
  56.             DBContext.SaveChanges();           
  57.             
  58.             Response.Write("<script>javascript:alert('Employee Information Deleted successfully');</script>");  
  59.            
  60.   
  61.         }  
  62.   
  63.         protected void EmployeeList_SelectedIndexChanged(object sender, EventArgs e)  
  64.         {  
  65.             EmployeeList.DataBind();  
  66.             Response.Write("<script>Window.location.reload()</script>");  
  67.   
  68.         }  
  69.   
  70.         protected void AddEmployeeButton_Click(object sender, EventArgs e)  
  71.         {  
  72.             // Add product data to DB.  
  73.             Employee newEmployee = new Employee();  
  74.             newEmployee.Id = int.Parse(AddId.Text);  
  75.             newEmployee.FirstName = AddFirstName.Text;  
  76.             newEmployee.LastName = AddLastName.Text;  
  77.             newEmployee.Salary = int.Parse(AddSalary.Text);  
  78.             newEmployee.ContactNo = AddContactNo.Text;  
  79.             newEmployee.Date_Of_Birth = AddDOB.Text;  
  80.             DBContext.Employees.Add(newEmployee);  
  81.             DBContext.SaveChanges();           
  82.             Response.Write("<script>javascript:alert('Employee Information Added  successfully');</script>");  
  83.              
  84.   
  85.         }  
  86.   
  87.         public void UpdateEmployee(Employee modifiedEmployee)  
  88.         {  
  89.             Employee oEmployee = DBContext.Employees.FirstOrDefault(i => i.Id == modifiedEmployee.Id);  
  90.             oEmployee.Id = modifiedEmployee.Id;  
  91.             oEmployee.FirstName = modifiedEmployee.FirstName;  
  92.             oEmployee.LastName = modifiedEmployee.LastName;  
  93.             oEmployee.Salary = modifiedEmployee.Salary;  
  94.             oEmployee.ContactNo = modifiedEmployee.ContactNo;  
  95.             oEmployee.Date_Of_Birth = modifiedEmployee.Date_Of_Birth;  
  96.             DBContext.SaveChanges();  
  97.             Response.Write("<script>javascript:alert('Employee Information Updated successfully');</script>");            
  98.               
  99.   
  100.         }  
  101.   
  102.     }  
  103. }  

Web.Config File 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!--  
  3.   For more information on how to configure your ASP.NET application, please visit  
  4.   http://go.microsoft.com/fwlink/?LinkId=169433  
  5.   -->  
  6. <configuration>  
  7.   <configSections>  
  8.     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />  
  9.     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->  
  10.   </configSections>  
  11.   <system.web>  
  12.     <compilation debug="true" targetFramework="4.5" />  
  13.     <httpRuntime targetFramework="4.5" />  
  14.     <pages>  
  15.       <namespaces>  
  16.         <add namespace="System.Web.Optimization" />  
  17.       </namespaces>  
  18.       <controls>  
  19.         <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />  
  20.       </controls>  
  21.     </pages>  
  22.   </system.web>  
  23.   <runtime>  
  24.     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
  25.       <dependentAssembly>  
  26.         <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />  
  27.         <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />  
  28.       </dependentAssembly>  
  29.     </assemblyBinding>  
  30.   </runtime>  
  31.   <connectionStrings>  
  32.     <add name="TutorialEntities" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Tutorial.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  33.   </connectionStrings>  
  34.   <entityFramework>  
  35.     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">  
  36.       <parameters>  
  37.         <parameter value="v11.0" />  
  38.       </parameters>  
  39.     </defaultConnectionFactory>  
  40.     <providers>  
  41.       <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />  
  42.     </providers>  
  43.   </entityFramework>  
  44. </configuration>  

Creating Database File Tutorial.mdf

Right-click on the App_Data folder and choose Add >> New Item >> New SQL Server Database.

List View Control With CRUD And Search Record 

Name it as Tutorial.mdf.

List View Control With CRUD And Search Record 

Now, we will be creating a table in the Microsoft database file, Tutorial.mdf, and manually inserting a few dummy records.

The newly created database file Tutorial.mdf is displayed inside the App_Data folder.

List View Control With CRUD And Search Record 

Right-click on Tutorial.mdf file and click "Open".

List View Control With CRUD And Search Record 

Right-click on Tables >> Add New Table.

List View Control With CRUD And Search Record 

Name the table as Employee and add six columns.

SQL of the table is mentioned below.

  1. CREATE TABLE [dbo].[Employee] (  
  2.     [Id]            INT           NOT NULL,  
  3.     [FirstName]     NVARCHAR (30) NULL,  
  4.     [LastName]      NVARCHAR (25) NULL,  
  5.     [Salary]        INT           NULL,  
  6.     [ContactNo]     NVARCHAR (30) NULL,  
  7.     [Date Of Birth] NVARCHAR(20)          NULL,  
  8.     PRIMARY KEY CLUSTERED ([Id] ASC)  
  9. );  

Click the "Update" button in the left corner and update the database in newly opened window.

List View Control With CRUD And Search Record 
 
List View Control With CRUD And Search Record 

A new table, Employee, is created. Refresh the Table folder in the Server Explorer window. The Employee table is there.

To add a record to the Employee table, right-click on it and select "Show Table Data".

There is no record. So, let us add dummy records.

List View Control With CRUD And Search Record

 

List View Control With CRUD And Search Record
 
Here is the SQL for records to insert.
  1. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (1, N'Stacy', N'Stewart', 5000, N'89765432987', N'1996-11-03')  
  2. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (2, N'Kevin', N'Sweetman', 6000, N'67987654387', N'1995-02-04')  
  3. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (3, N'Steve', N'Perry', 7500, N'76987432167', N'1993-02-05')  
  4. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (4, N'Mike', N'Ponting', 8300, N'87098654327', N'1995-02-01')  
  5. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (5, N'Rick', N'Rabjohn', 74000, N'54765432876', N'2000-05-06')  
  6. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (6, N'Sibu', N'Patra', 6500, N'879054321', N'2000-08-23')  
  7. INSERT INTO [dbo].[Employee] ([Id], [FirstName], [LastName], [Salary], [ContactNo], [Date Of Birth]) VALUES (7, N'Sibu', N'Patra', 6500, N'879054321', N'2000-08-23')  

Creating a Model to insert into Employee Database (Entity Framework Database First)

Create a new folder by right-clicking the project node >> Add >> NewFolde. Name it as "Models".

Right-click on the "Models" folder and from the opened menu list, click Add >> New Item >> ADO.NET Entity Data Model. Now, name it as EmpModel.edmex.

List View Control With CRUD And Search Record 
 
List View Control With CRUD And Search Record
 
List View Control With CRUD And Search Record 

Click on "New Connection" >> browse, and select database file Tutorial.mdf.

List View Control With CRUD And Search Record
 
List View Control With CRUD And Search Record 

Click "Test Connection".

List View Control With CRUD And Search Record 
 
List View Control With CRUD And Search Record 

Click Next >> Employee Table, as displayed below. Then, click "Finish".

List View Control With CRUD And Search Record
 
List View Control With CRUD And Search Record 

Click OK. Again, click OK and then, select the "Yes To All" button.

List View Control With CRUD And Search Record
 
List View Control With CRUD And Search Record
 
List View Control With CRUD And Search Record 

The web application ‘Employee Manager’ is shown below.

List View Control With CRUD And Search Record 

Add a record to it.

List View Control With CRUD And Search Record 
 
List View Control With CRUD And Search Record 

Here is how it will be searching for the FirstName or LastName containing the letter ‘S’.

List View Control With CRUD And Search Record 

Edit the records like below.

List View Control With CRUD And Search Record 

Delete the Records like below.

List View Control With CRUD And Search Record 

That's It. We have successfully built the CRUD Application in ASP.NET. Suggestions for modification are welcome.


Similar Articles