3 Tier Architecture in Asp.net Using C Example Suresh

N-tier application architecture provides a model for developers to create a flexible and reusable application by breaking up an application into tier. The n-Tier application has mainly three tiers or layers; they are called:

1. Presentation Layer

2. Business Logic Layer

3. Data Access Layer

Each layer interacts with the layer directly below, and has specific function to perform.

The Presentation Layer is responsible for displaying the user interface to the end user. The programmer uses this layer for designing the user interface and to transfer data. In ASP.NET, ASPX pages, user controls, server is used to support the presentation layer.

The Business Logic Layer  contains all the calculations and Business Rule validations that are required in the application.

Business Logic Layer is the class in which we write functions that get data from Presentation Layer and send that data to database through Data Access Layer. The business layer works as a go-between to transfer the data from presentation layer.Its responsibility is to validate the business rules of the component and communicating with the Data Access Layer.

The Data Access Layer gets the data from the business layer and sends it to the database or vice versa. DAL is responsible for accessing data and forwarding it to BLL. In an ASP.NET n-Tiered architecture, web pages do not make direct calls to the database. A given layer only communicates with its adjacent layers.

Now, Talking about What is the need to divide our code in 3-Tier Architecture? Separation of User Interface, Business Logic and Database Access has many advantages.

  • Reusability of Business Logic Component will help you for Quick Development. Let's take an example : We have a module that's functionality is to perform Adding New Records, Updating Existing Record, Deleting Existing Record and Finding the Record in the System. As this component is developed and tested, we can use it in any other project that might involve performing these tasks on records.
  • Transformation of the system is easy. Since the Business Logic is separate from the Data Access Layer, changing the data access layer won't affect the business logic module much. Let's say if we are moving from SQL Server data storage to Oracle, there shouldn't be any changes required in the business layer component and in the GUI component.
  • Maintenance of the system is easy. Let's say if there is a minor change in the business logic, we don't have to install the entire system in individual user's PCs. Let suppose that the government increases the Entertainment tax rate from 4% to 8 %, we only need to update the business logic component without affecting the productivity of end users and without any downtime.
  • Using 3-Tier Architecture development allows you parallel development on individual tier.

Here is the example that I have created using 3-Tier Architecture Concept. For ease of understanding I have separated the Presentation Layer, Business Access Layer and Data Access Layer.  I have created BAL and DAL into App_Code Folder.

Here is the Screenshot of the Solution Explorer:

N-Tier Architecture in ASP.NET

Lest Start with Coding. Firstly we will go with Data Access Layer then Business Access Layer and then Presentation Layer (UI).

Creating Data Access Layer (DAL): (RecordDAL.cs)

Add a Class File by Right Clicking on App_Code Folder and name itRecordDAL.cs (In my case I have created it in DAL Folder which is Under App_Code>3-Tier Folder. Below are the codes that I have written forRecordDAL.cs file. Here I have used Stored Procedure to perform the operations in Database.

using  System;

using  System.Collections.Generic;

using  System.Linq;

using  System.Web;

using  System.Data.SqlClient;

using  System.Data;

/// <summary>

///  Summary description for RecordDAL

/// </summary>

public classRecordDAL

{

// Getting Connection String that i have created in web.config file

string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["3Tier_ConnectionString"].ConnectionString;

public RecordDAL()

       {

       }

// Used to Insert Records in Database

publicint InsertRecord(string FName,string LName,string FatherName,int Age,string Address,stringPhone,string Email,int UserID)

    {

//Creating Connection with SQL Server Database

SqlConnection con =newSqlConnection(conStr);

        con.Open();

SqlCommand cmd =newSqlCommand("AddRecords",con);

        cmd.CommandType =CommandType.StoredProcedure;

try

        {

            cmd.Parameters.AddWithValue("@FName", FName);

            cmd.Parameters.AddWithValue("@LName", LName);

            cmd.Parameters.AddWithValue("@FatherName", FatherName);

            cmd.Parameters.AddWithValue("@Age", Age);

            cmd.Parameters.AddWithValue("@Address", Address);

            cmd.Parameters.AddWithValue("@Phone", Phone);

            cmd.Parameters.AddWithValue("@Email", Email);

            cmd.Parameters.AddWithValue("@UserID", UserID);

return cmd.ExecuteNonQuery();

        }

catch (Exception ex)

        {

throw;

        }

finally

        {

            con.Close();

            con.Dispose();

        }

    }

//Used to Delete Records from the Database

//This will take UserID as Input Parameter.

publicint DeleteRecord(int UserId)

    {

SqlConnection con =newSqlConnection(conStr);

        con.Open();

SqlCommand cmd =newSqlCommand("DeleteRecord",con);

        cmd.CommandType =CommandType.StoredProcedure;

try

        {

            cmd.Parameters.AddWithValue("@UserId",UserId);

return cmd.ExecuteNonQuery();

        }

catch (Exception ex)

        {

throw;

        }

finally

        {

            con.Close();

            con.Dispose();

        }

    }

//Used to Update Records in the Database

//This will take UserID as Input Parameter.

publicint UpdateRecord(string FName,string LName,string FatherName,int Age,string Address,string Phone,string Email,int UserID)

    {

SqlConnection con =newSqlConnection(conStr);

        con.Open();

SqlCommand cmd =newSqlCommand("UpdateRecord", con);

        cmd.CommandType =CommandType.StoredProcedure;

try

        {

            cmd.Parameters.AddWithValue("@FName", FName);

            cmd.Parameters.AddWithValue("@LName", LName);

            cmd.Parameters.AddWithValue("@FatherName", FatherName);

            cmd.Parameters.AddWithValue("@Age", Age);

            cmd.Parameters.AddWithValue("@Address", Address);

            cmd.Parameters.AddWithValue("@Phone", Phone);

            cmd.Parameters.AddWithValue("@Email", Email);

            cmd.Parameters.AddWithValue("@UserID", UserID);

return cmd.ExecuteNonQuery();

        }

catch (Exception ex)

        {

throw;

        }

finally

        {

            con.Close();

            con.Dispose();

        }

    }

// used to Load All the Records from the Database

publicDataTable RetrieveRecords()

    {

SqlConnection con =newSqlConnection(conStr);

SqlDataAdapter da =newSqlDataAdapter("ShowAllRecords", con);

        da.SelectCommand.CommandType =CommandType.StoredProcedure;

SqlCommandBuilder bui =newSqlCommandBuilder(da);

DataTable dt =newDataTable();

try

        {

            da.Fill(dt);

return dt;

        }

catch

        {

throw;

        }

finally

        {

            da.Dispose();

            con.Close();

            con.Dispose();

        }

    }

// Used to Check the existance of the Record.

publicint checkExistance(int UserId)

    {

SqlConnection con =newSqlConnection(conStr);

        con.Open();

SqlCommand cmd =newSqlCommand("Select * from tblUserInfo where UserID=" + UserId +"", con);

SqlDataReader dr;

try

        {

            dr = cmd.ExecuteReader();

if (dr.Read())

            {

return 1;

            }

else

return 0;

        }

catch (Exception ex)

        {

throw;

        }

finally

        {

            con.Close();

            con.Dispose();

        }

    }

}

In the above code, I have a member variable called conStr that is used to get the database connection string from myweb.config file that is being used throughout the class. I have created separate method for inserting, deleting, updating records into database and loading records from database. At the End of the Article I have given the Structure of Respective tables and Used Procedures.

Creating Business Access Layer (BAL):   (RecordBAL.cs)

Add a Class File by Right Clicking on App_Code Folder and name itRecordBAL.cs, (In my case I have created it in BAL Folder which is Under App_Code>3-Tier Folder. This contains methods that are used for calling InsertRecord  (), DeleteRecord (),

RetrieveRecords () and checkExistance () method of Data Access Layer Class File.  Below are the codes that I have written for RecordBAL.cs file.

using  System;

using  System.Collections.Generic;

using  System.Linq;

using  System.Web;

using  System.Data;

/// <summary>

///  Summary description for RecordBAL

/// </summary>

public classRecordBAL

{

public RecordBAL()

       {

       }

//Used for Loading All Records from Database

publicDataTable RetrieveRecords()

    {

//Creating the object of DAL file.

RecordDAL rdAL =newRecordDAL();

try

        {

//Calling the method of DAl using DAL object

//and return the result to the caller of the method.

return rdAL.RetrieveRecords();

        }

catch

        {

throw;

        }

finally

        {

            rdAL =null;

        }

    }

//Used for Inserting Record in the Database

publicint InsertRecord_BAL(string FName,string LName,string FatherName,int Age,string Address,string Phone,string Email,int UserID)

    {

RecordDAL rDal =newRecordDAL();

try

        {

return rDal.InsertRecord( FName,LName,FatherName,Age,Address,Phone,Email,UserID);

        }

catch

        {

throw;

        }

finally

        {

            rDal =null;

        }

    }

// Used for Deleting the Records from the Database

publicint DeleteRecord_BAL(int UserID)

    {

RecordDAL rDal =newRecordDAL();

try

        {

return rDal.DeleteRecord(UserID);

        }

catch

        {

throw;

        }

finally

        {

            rDal =null;

        }

    }

//Used for Updating Record in Database

publicint UpdateRecord_BAL(string FName,string LName,string FatherName,int Age,string Address,string Phone,string Email,int UserID)

    {

RecordDAL rDal =newRecordDAL();

try

        {

return rDal.UpdateRecord(FName, LName, FatherName, Age, Address, Phone, Email, UserID);

        }

catch

        {

throw;

        }

finally

        {

            rDal =null;

        }

    }

// Used for checking exixtance of the Record in the Database

publicint checkExistance_BAL(int UserID)

    {

RecordDAL rDal =newRecordDAL();

try

        {

return rDal.checkExistance(UserID);

        }

catch (Exception ex)

        {

throw;

        }

finally

        {

            rDal =null;

        }

    }

}

Creating Presentation Layer (UI): (Default.aspx)

Till Now, we have created our Data Access Layer (DAL), Business Access Layer (BAL). Now, we are going to create our Presentation Layer that is User Interface (UI), it will accept the value from the user. Add a new WebPage to your project. Here I named itDefault.aspx

Here is the Screenshot of the UI that I have created to accept the values from the user.

N-Tier Architecture in ASP.NET

Code for Default.aspx file

<% @PageLanguage ="C#"AutoEventWireup ="true"CodeFile ="Default.aspx.cs" Inherits ="_Default"%>

<! DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

< htmlxmlns ="http://www.w3.org/1999/xhtml">

< headrunat ="server">

< title >Add New Records (3-Tier Architecture in ASP.NET)</ title >

< scripttype ="text/javascript">

// This will prevent to Go Back

        window.history.forward(0);

function noBack()

        {

            window.history.forward();

        }

//This will take the ref of textbox and will trim the white-spaces

function trim(id) {

if (id !=null)

                id.value = id.value.toString().replace(/^\s+|\s+$/g,"");

        }

</ script >

</ head >

< body>

< formid ="form1"runat ="server">

< divstyle =" margin :0 auto; width :700px; text-align :center">

< tablestyle =" margin :0 auto;"width ="400px">

< tr >

< tdcolspan ="2"align ="center"bgcolor ="#99CCFF">

< asp : LabelID ="Label1"runat ="server"Text ="Add New Records"Font-Bold ="True"

Font-Names ="Georgia"ForeColor ="#0033CC"></ asp : Label >

&nbsp; </ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label8"runat ="server"Text ="User ID"></ asp : Label >

</ td >

< tdalign ="left">

< asp : TextBoxID ="txtUserID"runat ="server"Width ="180px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator8"runat ="server"

ControlToValidate ="txtUserID"ErrorMessage ="*"

ToolTip ="Provi User ID"></ asp : RequiredFieldValidator >

< asp : RegularExpressionValidatorID ="RegularExpressionValidator3" runat ="server"

ControlToValidate ="txtUserID"ToolTip ="This Will Take Number Only (Ex: 1)"

ErrorMessage ="*"ValidationExpression ="^[0-9]+$"></ asp : RegularExpressionValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label2"runat ="server"Text ="First Name"></ asp : Label >

</ td >

< tdalign ="left">

< asp : TextBoxID ="txtFName"runat ="server"Width ="180px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator1"runat ="server"

ControlToValidate ="txtFName"ErrorMessage ="*"

ToolTip ="First Name Can't be Left Blank"></ asp : RequiredFieldValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label3"runat ="server"Text ="Last Name"></ asp : Label >

</ td >

< tdalign ="left">

< asp : TextBoxID ="txtLName"runat ="server"Width ="180px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator2"runat ="server"

ControlToValidate ="txtLName"ErrorMessage ="*"

ToolTip ="Last Name Can't Be Left Blank"></ asp : RequiredFieldValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label4"runat ="server"Text ="Father Name"></ asp : Label >

</ td >

< tdalign ="left">

< asp : TextBoxID ="txtFatherName"runat ="server"Width ="180px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator3"runat ="server"

ControlToValidate ="txtFatherName"ErrorMessage ="*"

ToolTip ="Father Name Can't Be Left Blank"></ asp : RequiredFieldValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label5"runat ="server"Text ="Age"></ asp : Label >

</ td >

< tdclass ="style3"align ="left">

< asp : TextBoxID ="txtAge"runat ="server"Width ="100px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator4"runat ="server"

ControlToValidate ="txtAge"ErrorMessage ="*"ToolTip ="Age Can't Be Left Blank"></ asp : RequiredFieldValidator >

< asp : RegularExpressionValidatorID ="RegularExpressionValidator2" runat ="server"

ControlToValidate ="txtAge"ToolTip ="Enter Numbers Only (Ex: 25)" ErrorMessage ="*"ValidationExpression ="^[0-9]+$"></ asp : RegularExpressionValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label6"runat ="server"Text ="Address"></ asp : Label >

</ td >

< tdalign ="left">

< asp : TextBoxID ="txtAddress"runat ="server"Height ="49px" TextMode ="MultiLine"

Width ="180px"onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator5"runat ="server"

ControlToValidate ="txtAddress"ErrorMessage ="*"

ToolTip ="Provide Address Details"></ asp : RequiredFieldValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

< asp : LabelID ="Label7"runat ="server"Text ="Phone No."></ asp : Label >

</ td >

< tdalign ="left">

< asp : TextBoxID ="txtPhone"runat ="server"Width ="180px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator6"runat ="server"

ControlToValidate ="txtPhone"ErrorMessage ="*"

ToolTip ="Provide Phone Details"></ asp : RequiredFieldValidator >

< asp : RegularExpressionValidatorID ="RegularExpressionValidator4" runat ="server"

ControlToValidate ="txtPhone"

ToolTip ="This Will Take Number Only (Ex: 9889989898)" ErrorMessage ="*"

ValidationExpression ="^[0-9]+$"></ asp : RegularExpressionValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

                    Email ID</ td >

< tdalign ="left">

< asp : TextBoxID ="txtEmail"runat ="server"Width ="180px" onblur ="trim(this)"></ asp : TextBox >

< asp : RequiredFieldValidatorID ="RequiredFieldValidator7"runat ="server"

ControlToValidate ="txtEmail"ErrorMessage ="*"ToolTip ="Provide Email ID"></ asp : RequiredFieldValidator >

< asp : RegularExpressionValidatorID ="RegularExpressionValidator1" runat ="server"ErrorMessage ="*"

ToolTip ="Invalid Email Format. (Ex: abc@xyz.com)"

ValidationExpression ="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

ControlToValidate ="txtEmail"></ asp : RegularExpressionValidator >

</ td >

</ tr >

< tr >

< tdalign ="right">

&nbsp; </ td >

< tdalign ="left">

< asp : ButtonID ="btnSave"runat ="server"Text ="Save"Width ="95px"

onclick ="btnSave_Click"Font-Bold ="True"Font-Names ="Georgia"/>

< asp : HyperLinkID ="HyperLink1"runat ="server" NavigateUrl ="ShowRecords.aspx">Show Records</ asp : HyperLink >

</ td >

</ tr >

< tr >

< tdalign ="right">

&nbsp; </ td >

< tdalign ="left">

< asp : LabelID ="lblMessage"runat ="server"Font-Bold ="True"Font-Names ="Georgia"

Font-Size ="Medium"ForeColor ="Red"></ asp : Label >

</ td >

</ tr >

< tr >

< tdalign ="right"colspan ="2">

< hrstyle =" border-color : #6699FF; background-color : #99CCFF"/>

&nbsp; </ td >

</ tr >

</ table >

</ div >

</ form >

</ body >

</ html >

The above code contains all the validation on User Input. Like Text Can't Be Left Blank, Only Numbers in TextBox, Only Alphabets in TextBox, and Email Format Validation at client-side. It will also check that whether the record already exists in database.

Code for Default.aspx.cs file

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;

publicpartialclass_Default : System.Web.UI.Page

{

protectedvoid Page_Load(object sender,EventArgs e)

    {

    }

protectedvoid btnSave_Click(object sender,EventArgs e)

    {

//Creating the object of BAL

RecordBAL rBAL=newRecordBAL();

int recordStatus = 0;

string FName=txtFName.Text.ToString();

string LName=txtLName.Text.ToString();

string FatherName=txtFatherName.Text.ToString();

int Age=Convert.ToInt32( txtAge.Text);

string Address=txtAddress.Text.ToString();

string Phone=txtPhone.Text.ToString();

string Email=txtEmail.Text.ToString();

int UserID=Convert.ToInt32(txtUserID.Text);

try

        {

//Passing the Parameter in the Method of BAl using BAL object

            recordStatus = rBAL.checkExistance_BAL(UserID);

if (recordStatus > 0)

            {

                lblMessage.Text ="This User ID Already Exists.";

return;

            }

            recordStatus = rBAL.InsertRecord_BAL(FName, LName, FatherName, Age, Address, Phone, Email, UserID);

if(recordStatus > 0)

                lblMessage.Text ="New Record Inserted Successfully.";

//else

//    lblMessage.Text = "This Record Already Exists.";

        }

catch (Exception ex)

        {

            lblMessage.Text = ex.Message.ToString();

        }

finally

        {

            rBAL =null;

        }

    }

}

Now, to display the records, I have created another page and named it ShowRecords.aspx. Here is the Screenshot of the UI of ShowRecords.aspx

ShowRecords.aspx (UI)

N-Tier Architecture in ASP.NET

This will get all the Record from the database and display it in GridView. Here I have make the GridView Editable to enable it to perform Update and Delete Operation. You can Perform Update Operation by Clicking onEdit  Button and can perform Delete Operation by Clicking Delete  Button in GridView.

Code for ShowRecords.aspx file

<% @PageLanguage ="C#"AutoEventWireup ="true"CodeFile ="ShowRecords.aspx.cs" Inherits ="ShowRecords"%>

<! DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

< htmlxmlns ="http://www.w3.org/1999/xhtml">

< headrunat ="server">

< title >List of All Records (3-Tier Architecture in ASP.NET)</ title >

< scripttype ="text/javascript">

        window.history.forward(0);

function noBack()

        {

            window.history.forward();

        }

function trim(id) {

if (id !=null)

                id.value = id.value.toString().replace(/^\s+|\s+$/g,"");

        }

</ script >

</ head >

< body >

< formid ="form1"runat ="server">

< divstyle =" margin : 0 auto;"width ="1100px">

< tablestyle =" margin : 0 auto;"width ="1100px">

< tr >

< td >

< asp : HyperLinkID ="HyperLink1"runat ="server"

NavigateUrl ="~/3-Tier/Default.aspx">Add New Record</ asp : HyperLink >

</ td >

</ tr >

< tr >

< tdbgcolor ="#6699FF"align ="center">

&nbsp;

< asp : LabelID ="Label1"runat ="server"Font-Bold ="True"Font-Names ="Georgia"ForeColor ="White"

Text ="List of All Records"></ asp : Label >

</ td >

</ tr >

< tr >

< tdalign ="center">

< asp : GridViewID ="GridViewShowRecords"runat ="server"BackColor ="White" BorderColor ="#DEDFDE"

BorderStyle ="None"BorderWidth ="1px"CellPadding ="4" EnableModelValidation ="True"

ForeColor ="Black"GridLines ="Vertical"AutoGenerateColumns ="false" OnRowCancelingEdit ="RowCancelingEdit"

OnRowDeleting ="RowDeleting"OnRowEditing ="RowEditing" OnRowUpdating ="RowUpdating">

< AlternatingRowStyleBackColor ="White"/>

< FooterStyleBackColor ="#CCCC99"/>

< HeaderStyleBackColor ="#6B696B"Font-Bold ="True"ForeColor ="White" />

< PagerStyleBackColor ="#F7F7DE"ForeColor ="Black" HorizontalAlign ="Right"/>

< RowStyleBackColor ="#F7F7DE"/>

< SelectedRowStyleBackColor ="#CE5D5A"Font-Bold ="True" ForeColor ="White"/>

< Columns >

< asp : TemplateField >

< HeaderTemplate >

                                    ID</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblUserID"runat ="server" Text =' <% #Bind("UserId")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtUserID"Text =' <% #Bind("UserId")%> ' runat ="server"Width ="20px"

Enabled ="False"></ asp : TextBox >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    FirstName</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblFirstName"runat ="server" Text =' <% #Bind("FName")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtFirstName"Text =' <% #Bind("FName")%> 'runat ="server"Width ="80px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator1"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtFirstName"ToolTip ="Can't Be Left Blank.">*</ asp : RequiredFieldValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    LastName</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblLastName"runat ="server" Text =' <% #Bind("LName")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtLastName"Text =' <% #Bind("LName")%> 'runat ="server"Width ="80px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator2"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtLastName"ToolTip ="Can't Be Left Blank.">*</ asp : RequiredFieldValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    FatherName</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblFatherName"runat ="server" Text =' <% #Bind("FatherName")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtFatherName" Text =' <% #Bind("FatherName")%> 'runat ="server"Width ="100px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator3"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtFatherName"ToolTip ="Can't Be Left Blank.">*</ asp : RequiredFieldValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    Age</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblAge"runat ="server" Text =' <% #Bind("Age")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtAge"Text =' <% #Bind("Age")%> ' runat ="server"Width ="30px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator4"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtAge"ToolTip ="Provide Age Details.(EX: 24)">*</ asp : RequiredFieldValidator >

< asp : RegularExpressionValidator ID ="RegularExpressionValidator2"runat ="server"ControlToValidate ="txtAge"

ToolTip ="Enter Numbers Only (Ex: 25)" ErrorMessage ="*"ValidationExpression ="^[0-9]+$"></ asp : RegularExpressionValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    Address</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblAddress"runat ="server" Text =' <% #Bind("Address")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtAddress"Text =' <% #Bind("Address")%> 'runat ="server"Width ="150px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator5"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtAddress"ToolTip ="Provide Address Details.">*</ asp : RequiredFieldValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    Phone</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblPhone"runat ="server" Text =' <% #Bind("Phone")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtPhone"Text =' <% #Bind("Phone")%> ' runat ="server"Width ="80px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator6"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtPhone"ToolTip ="Provide Phone No. Details.">*</ asp : RequiredFieldValidator >

< asp : RegularExpressionValidator ID ="RegularExpressionValidator4"runat ="server"ControlToValidate ="txtPhone"

ToolTip ="This Will Take Number Only (Ex: 9889989898)"ErrorMessage ="*"ValidationExpression ="^[0-9]+$"></ asp : RegularExpressionValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    Email</ HeaderTemplate >

< ItemTemplate >

< asp : LabelID ="lblEmail"runat ="server" Text =' <% #Bind("Email")%> '></ asp : Label >

</ ItemTemplate >

< EditItemTemplate >

< asp : TextBoxID ="txtEmail"Text =' <% #Bind("Email")%> ' runat ="server"Width ="120px"></ asp : TextBox >

< asp : RequiredFieldValidator ID ="RequiredFieldValidator7"runat ="server"ErrorMessage ="RequiredFieldValidator"

ControlToValidate ="txtEmail"ToolTip ="Provide Email Details.(EX: abc@xyz.com)">*</ asp : RequiredFieldValidator >

< asp : RegularExpressionValidator ID ="RegularExpressionValidator1"runat ="server"ErrorMessage ="*"

ToolTip ="Invalid Email Format. (Ex: abc@xyz.com)" ValidationExpression ="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

ControlToValidate ="txtEmail"></ asp : RegularExpressionValidator >

</ EditItemTemplate >

</ asp : TemplateField >

< asp : TemplateField >

< HeaderTemplate >

                                    Command Button</ HeaderTemplate >

< ItemTemplate >

< asp : ButtonID ="btnEdit"runat ="server" CommandName ="Edit"Text ="Edit"/>

< asp : ButtonID ="btnDelete"runat ="server" CommandName ="Delete"Text ="Delete"CausesValidation ="true"

OnClientClick ="return confirm('Are you sure?')" /></ ItemTemplate >

< EditItemTemplate >

< asp : ButtonID ="btnUpdate"runat ="server" CommandName ="Update"Text ="Update"/>

< asp : ButtonID ="btnCancel"runat ="server" CommandName ="Cancel"Text ="Cancel"CausesValidation ="false"/>

</ EditItemTemplate >

</ asp : TemplateField >

</ Columns >

</ asp : GridView >

</ td >

</ tr >

< tr >

< td >

< asp : LabelID ="lblMessage"runat ="server"Font-Bold ="True"Font-Names ="Georgia"ForeColor ="Red"></ asp : Label >

</ td >

</ tr >

< tr >

< td >

< hrstyle =" border-color : #6699FF"/>

</ td >

</ tr >

</ table >

</ div >

</ form >

</ body >

</ html >

Code for ShowRecords.aspx.cs file

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

publicpartialclassShowRecords : System.Web.UI.Page

{

protectedvoid Page_Load(object sender,EventArgs e)

    {

if (!IsPostBack)

        {

//Binding the GridView

            BindGridViewShowRecords();

        }

    }

privatevoid BindGridViewShowRecords()

    {

//Setting the DataSource of GridView

        GridViewShowRecords.DataSource = GridShowRecordsDataSource();

        GridViewShowRecords.DataBind();

    }

privateDataTable GridShowRecordsDataSource()

    {

//Creating object of BAL

RecordBAL rBAL =newRecordBAL();

DataTable dTable =newDataTable();

try

        {

//Getting the DataSource for GridView from BAL Using BAL object

            dTable = rBAL.RetrieveRecords();

        }

catch (Exception ex)

        {

           lblMessage.Text = ex.Message.ToString();

        }

finally

        {

            rBAL =null;

        }

return dTable;

    }

protectedvoid RowCancelingEdit(object sender,GridViewCancelEditEventArgs e)

    {

        GridViewShowRecords.EditIndex = -1;

        BindGridViewShowRecords();

    }

protectedvoid RowEditing(object sender,GridViewEditEventArgs e)

    {

        GridViewShowRecords.EditIndex = e.NewEditIndex;

        BindGridViewShowRecords();

    }

protectedvoid RowUpdating(object sender,GridViewUpdateEventArgs e)

    {

int recordStatus = 0;

try

        {

TextBox UserID = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtUserID")asTextBox;

TextBox FName = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtFirstName")asTextBox;

TextBox LName = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtLastName")asTextBox;

TextBox FatherName = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtFatherName")asTextBox;

TextBox Age = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtAge")asTextBox;

TextBox Address = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtAddress")asTextBox;

TextBox Phone = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtPhone")asTextBox;

TextBox Email = GridViewShowRecords.Rows[e.RowIndex].FindControl("txtEmail")asTextBox;

RecordBAL rBAL =newRecordBAL();

try

            {

                recordStatus = rBAL.UpdateRecord_BAL(FName.Text.Trim(),LName.Text.Trim(),FatherName.Text.Trim(),Convert.ToInt32(Age.Text.Trim()),Address.Text.Trim(),

Phone.Text.Trim(),Email.Text.Trim(),Convert.ToInt32( UserID.Text.Trim()));

if (recordStatus > 0)

                    lblMessage.Text ="Record Updated Successfully.";

else

                   lblMessage.Text ="Record couldn't updated";

            }

catch (Exception ee)

            {

               lblMessage.Text = ee.Message.ToString();

            }

finally

            {

                rBAL =null;

            }

            GridViewShowRecords.EditIndex = -1;

            BindGridViewShowRecords();

        }

catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

    }

protectedvoid RowDeleting(object sender,GridViewDeleteEventArgs e)

    {

int recordStatus = 0;

Label UserID = GridViewShowRecords.Rows[e.RowIndex].FindControl("lblUserID")asLabel;

int id =Convert.ToInt32(UserID.Text);

RecordBAL rBAL =newRecordBAL();

try

        {

            recordStatus = rBAL.DeleteRecord_BAL(id);

if (recordStatus > 0)

                lblMessage.Text ="Record Deleted Successfully.";

else

                lblMessage.Text ="Record couldn't Deleted";

        }

catch (Exception ee)

        {

            lblMessage.Text = ee.Message.ToString();

        }

finally

        {

            rBAL =null;

        }

        GridViewShowRecords.EditIndex = -1;

        BindGridViewShowRecords();

    }

}

 Following are the Screenshots of the output window of the program.

N-Tier Architecture in ASP.NET

N-Tier Architecture in ASP.NET

Database Structure

Following are the structure of the Respective Tables and Stored Procedures used in this example.

tblUserInfo

CREATE TABLE  [dbo] .[tblUserInfo]

(

      [FName] [varchar] (100) NOT NULL,

      [LName] [varchar] (100) NULL,

      [FatherName] [varchar] (100) NULL,

      [Age] [int] NULL,

      [Address] [varchar] (200) NULL,

      [Phone] [varchar] (20) NULL,

      [Email] [varchar] (50) NULL,

      [UserID] [int] primary key ,

)

Stored Procedure

AddRecords

CREATE PROCEDURE  [dbo] .[AddRecords]

(

            @FName varchar (100),

            @LName varchar (100),

            @FatherName varchar (100),

            @Age int ,

            @Address varchar (200),

            @Phone varchar (20),

            @Email varchar (50),

            @UserID int

)

AS

insert into  tblUserInfo

(FName,LName,FatherName,Age, Address ,Phone,Email,UserID)

values

(@FName,@LName,@FatherName,@Age,@Address,@Phone,@Email,@UserID)

RETURN

GO

UpdateRecord

CREATE PROCEDURE  [dbo] .[UpdateRecord]

(

            @FName varchar (100),

            @LName varchar (100),

            @FatherName varchar (100),

            @Age int ,

            @Address varchar (200),

            @Phone varchar (20),

            @Email varchar (50),

            @UserID int

)

AS

update  tblUserInfo

set

            FName =@FName,

            LName =@LName,

            FatherName =@FatherName,

            Age =@Age,

Address =@Address,

            Phone =@Phone,

            Email =@Email

where

            UserID =  @UserID

RETURN

GO

DeleteRecord

CREATE PROCEDURE  [dbo] .[DeleteRecord]

(

      @UserId int

)

AS

delete from  tblUserInfo where  UserID =  @UserId

RETURN

GO

3 Tier Architecture in Asp.net Using C Example Suresh

Source: http://pankajtiwarii.blogspot.com/p/building-3-tier-application-using.html

0 Response to "3 Tier Architecture in Asp.net Using C Example Suresh"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel