3-Tier Architecture in asp.net using c#


3-Tier Architecture in asp.net using c#

In this asp.net tutorial you will learn how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it n-tier architecture. Layer architectures are essentially objects and work in object oriented environment just like asp.net. 3-tier architecture is a very well known architecture in the world of software development, it doesn’t matter whether you are developing web based application or desktop based, it is the best architecture to use.

3-Tier Architecture in asp.net using c#

3-Tier architecture consists of 1) UI or Presentation Layer 2) Business Access Layer or Business Logic Layer 3) Data Access Layer

Presentation Layer Presentation layer consists of pages like .aspx or desktop based form where data is presented to users or getting input from users. Business Logic layer or Business Access Layer Business logic layer contains all of the business logic. Its responsibility is to validate the business rules of the component and communicating with the Data Access Layer. 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. Data Access Layer Data Access Layer is also the class that contains methods to enable business logic layer to connect the data and perform desired actions. These desired actions can be selecting, inserting, updating and deleting the data. DAL accepts the data from BAL and sends it to the database or DAL gets the data from the database and sends it to the business layer. In short, its responsibility is to communicate with the backend structure. Illustration of 3-Tier Architecture with Diagram

3-Tier architecture in asp.net

The figure clearly describe about the purpose of BAL and DAL. The main advantage of 3-tier architecture is to separate the presentation layer from data access layer. You will not write any function to communicate with database in presentation layer, all the required functions for communication with database will be available in DataAcessLayer. Its mean at presentation layer you will just focus at information that you will present in front of user. I am going to create BAL, DAL in App_Codefolder. You can also create separate projects for BAL, DAL and UI (Your website) and referenced your DAL into BAL and BAL into UI. In that scenario you have to rebuild the DAL and BAL every time, in order to view the change that you have made in your BAL and DAL. So to get rid of rebuilding layers every time after change, I am going to create BAL and DAL folder in App_Code. Now feel free to make changes in BAL and DAL and just refresh the webpage to view the change that you made, in short no rebuilding of DAL and BAL is required. The following figure shows the 3-tier architecture of our website that we are going to made.

3-Tier architecture in asp.net

Design and implement 3-tier architecture

. 1) Open visual studio or visual web developer. 2) Go to File-> New Web Site

3) Select ASP.NET Web Site and then browse the Folder in which you want to save your web pages.

4) Go to Solution Explorer and then right click on your website folder. Go to Add ASP.NET Folder-> App_Code.

5) Now right click on App_Code Folder and select New Folder.

6) Create Two Folders and give BusinessLayer and DataAccessLayer names to them. 7) Now right click on DataAccessLayer -> Add New Item.

8) Select Class as template and give DbAccess name to that class.

9) Now right click on BusinessLayer folder-> Add New Item

10) Select Class as template and give BusComments.cs name to that class.

Now open your DbAccess.cs file placed in DataAccessLayer folder. Clear it by deleting all its built-in code and then copy/paste the following code in your DbAccess.cs file and then save it

DbAccess.cs

  1. using System;
  2. using System.Data;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data.SqlClient;
  7. using System.Web;
  8. namespace DataAccessLayer
  9. {
  10. /// <summary>
  11. /// Constains overloaded method to access database and run queries
  12. /// </summary>
  13. public class DbAccess
  14. {
  15. private SqlConnection DbConn = new SqlConnection();
  16. private SqlDataAdapter DbAdapter = new SqlDataAdapter();
  17. private SqlCommand DbCommand = new SqlCommand();
  18. private SqlTransaction DbTran;
  19. private string strConnString = ConfigurationManager.ConnectionStrings[“WebsiteConnectionString”].ToString();
  20. public void setConnString(string strConn)
  21. {
  22. try
  23. {
  24. strConnString = strConn;
  25. }
  26. catch (Exception exp)
  27. {
  28. throw exp;
  29. }
  30. }
  31. public string getConnString()
  32. {
  33. try
  34. {
  35. return strConnString;
  36. }
  37. catch (Exception exp)
  38. {
  39. throw exp;
  40. }
  41. }
  42. private void createConn()
  43. {
  44. try
  45. {
  46. DbConn.ConnectionString = strConnString;
  47. DbConn.Open();
  48. }
  49. catch (Exception exp)
  50. {
  51. throw exp;
  52. }
  53. }
  54. public void closeConnection()
  55. {
  56. try
  57. {
  58. if (DbConn.State != 0)
  59. DbConn.Close();
  60. }
  61. catch (Exception exp)
  62. {
  63. throw exp;
  64. }
  65. }
  66. public void beginTrans()
  67. {
  68. try
  69. {
  70. if (DbTran == null)
  71. {
  72. if (DbConn.State == 0)
  73. {
  74. createConn();
  75. }
  76. DbTran = DbConn.BeginTransaction();
  77. DbCommand.Transaction = DbTran;
  78. DbAdapter.SelectCommand.Transaction = DbTran;
  79. DbAdapter.InsertCommand.Transaction = DbTran;
  80. DbAdapter.UpdateCommand.Transaction = DbTran;
  81. DbAdapter.DeleteCommand.Transaction = DbTran;
  82. }
  83. }
  84. catch (Exception exp)
  85. {
  86. throw exp;
  87. }
  88. }
  89. public void commitTrans()
  90. {
  91. try
  92. {
  93. if (DbTran != null)
  94. {
  95. DbTran.Commit();
  96. DbTran = null;
  97. }
  98. }
  99. catch (Exception exp)
  100. {
  101. throw exp;
  102. }
  103. }
  104. public void rollbackTrans()
  105. {
  106. try
  107. {
  108. if (DbTran != null)
  109. {
  110. DbTran.Rollback();
  111. DbTran = null;
  112. }
  113. }
  114. catch (Exception exp)
  115. {
  116. throw exp;
  117. }
  118. }
  119. /// <summary>
  120. /// Fills the Dataset dset and its Table tblname via stored procedure provided as spName arguement.Takes Parameters as param
  121. /// </summary>
  122. /// <param name=”dSet”></param>
  123. /// <param name=”spName”></param>
  124. /// <param name=”param”></param>
  125. /// <param name=”tblName”></param>
  126. public void selectStoredProcedure(DataSet dSet, string spName, Hashtable param, string tblName)
  127. {
  128. try
  129. {
  130. if (DbConn.State == 0)
  131. {
  132. createConn();
  133. }
  134. DbCommand.Connection = DbConn;
  135. DbCommand.CommandText = spName;
  136. DbCommand.CommandType = CommandType.StoredProcedure;
  137. foreach (string para in param.Keys)
  138. {
  139. DbCommand.Parameters.AddWithValue(para, param[para]);
  140. }
  141. DbAdapter.SelectCommand = (DbCommand);
  142. DbAdapter.Fill(dSet, tblName);
  143. }
  144. catch (Exception exp)
  145. {
  146. throw exp;
  147. }
  148. }
  149. public void selectStoredProcedure(DataSet dSet, string spName, string tblName)
  150. {
  151. try
  152. {
  153. if (DbConn.State == 0)
  154. {
  155. createConn();
  156. }
  157. DbCommand.Connection = DbConn;
  158. DbCommand.CommandText = spName;
  159. DbCommand.CommandType = CommandType.StoredProcedure;
  160. DbAdapter.SelectCommand = DbCommand;
  161. DbAdapter.Fill(dSet, tblName);
  162. }
  163. catch (Exception exp)
  164. {
  165. throw exp;
  166. }
  167. }
  168. public void selectQuery(DataSet dSet, string query, string tblName)
  169. {
  170. try
  171. {
  172. if (DbConn.State == 0)
  173. {
  174. createConn();
  175. }
  176. DbCommand.CommandTimeout = 600;
  177. DbCommand.Connection = DbConn;
  178. DbCommand.CommandText = query;
  179. DbCommand.CommandType = CommandType.Text;
  180. DbAdapter = new SqlDataAdapter(DbCommand);
  181. DbAdapter.Fill(dSet, tblName);
  182. }
  183. catch (Exception exp)
  184. {
  185. DbAdapter.Dispose();
  186. DbConn.Close();
  187. throw exp;
  188. }
  189. finally
  190. {
  191. DbAdapter.Dispose();
  192. DbConn.Close();
  193. }
  194. }
  195. public int executeQuery(string query)
  196. {
  197. try
  198. {
  199. if (DbConn.State == 0)
  200. {
  201. createConn();
  202. }
  203. DbCommand.Connection = DbConn;
  204. DbCommand.CommandText = query;
  205. DbCommand.CommandType = CommandType.Text;
  206. return DbCommand.ExecuteNonQuery();
  207. }
  208. catch (Exception exp)
  209. {
  210. throw exp;
  211. }
  212. finally
  213. {
  214. DbAdapter.Dispose();
  215. DbConn.Close();
  216. }
  217. }
  218. public int executeStoredProcedure(string spName, Hashtable param)
  219. {
  220. try
  221. {
  222. if (DbConn.State == 0)
  223. {
  224. createConn();
  225. }
  226. DbCommand.Connection = DbConn;
  227. DbCommand.CommandText = spName;
  228. DbCommand.CommandType = CommandType.StoredProcedure;
  229. foreach (string para in param.Keys)
  230. {
  231. DbCommand.Parameters.AddWithValue(para, param[para]);
  232. }
  233. return DbCommand.ExecuteNonQuery();
  234. }
  235. catch (Exception exp)
  236. {
  237. throw exp;
  238. }
  239. }
  240. public int returnint32(string strSql)
  241. {
  242. try
  243. {
  244. if (DbConn.State == 0)
  245. {
  246. createConn();
  247. }
  248. else
  249. {
  250. DbConn.Close();
  251. createConn();
  252. }
  253. DbCommand.Connection = DbConn;
  254. DbCommand.CommandText = strSql;
  255. DbCommand.CommandType = CommandType.Text;
  256. return (int)DbCommand.ExecuteScalar();
  257. }
  258. catch (Exception exp)
  259. {
  260. return 0;
  261. }
  262. }
  263. public Int64 returnint64(string strSql)
  264. {
  265. try
  266. {
  267. if (DbConn.State == 0)
  268. {
  269. createConn();
  270. }
  271. DbCommand.Connection = DbConn;
  272. DbCommand.CommandText = strSql;
  273. DbCommand.CommandType = CommandType.Text;
  274. return (Int64)DbCommand.ExecuteScalar();
  275. }
  276. catch (Exception exp)
  277. {
  278. throw exp;
  279. }
  280. }
  281. public int executeDataSet(DataSet dSet, string tblName, string strSql)
  282. {
  283. try
  284. {
  285. if (DbConn.State == 0)
  286. {
  287. createConn();
  288. }
  289. DbAdapter.SelectCommand.CommandText = strSql;
  290. DbAdapter.SelectCommand.CommandType = CommandType.Text;
  291. SqlCommandBuilder DbCommandBuilder = new SqlCommandBuilder(DbAdapter);
  292. return DbAdapter.Update(dSet, tblName);
  293. }
  294. catch (Exception exp)
  295. {
  296. throw exp;
  297. }
  298. }
  299. public bool checkDbConnection()
  300. {
  301. int _flag = 0;
  302. try
  303. {
  304. if (DbConn.State == ConnectionState.Open)
  305. {
  306. DbConn.Close();
  307. }
  308. DbConn.ConnectionString = getConnString();
  309. DbConn.Open();
  310. _flag = 1;
  311. }
  312. catch (Exception ex)
  313. {
  314. _flag = 0;
  315. }
  316. if (_flag == 1)
  317. {
  318. DbConn.Close();
  319. _flag = 0;
  320. return true;
  321. }
  322. else
  323. {
  324. return false;
  325. }
  326. }
  327. public string GetColumnValue(string Query)
  328. {
  329. try
  330. {
  331. if (DbConn.State == 0)
  332. {
  333. createConn();
  334. }
  335. DbCommand.CommandTimeout = 120;
  336. DbCommand.Connection = DbConn;
  337. DbCommand.CommandType = CommandType.Text;
  338. DbCommand.CommandText = Query;
  339. object objResult = DbCommand.ExecuteScalar();
  340. if (objResult == null)
  341. {
  342. return “”;
  343. }
  344. if (objResult == System.DBNull.Value)
  345. {
  346. return “”;
  347. }
  348. else
  349. {
  350. return Convert.ToString(objResult);
  351. }
  352. }
  353. catch (Exception ex)
  354. {
  355. throw ex;
  356. }
  357. finally
  358. {
  359. DbAdapter.Dispose();
  360. DbConn.Close();
  361. }
  362. }
  363. }
  364. }
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;

namespace DataAccessLayer
{
/// <summary>
/// Constains overloaded method to access database and run queries
/// </summary>
public class DbAccess
{
private SqlConnection DbConn = new SqlConnection();
private SqlDataAdapter DbAdapter = new SqlDataAdapter();
private SqlCommand DbCommand = new SqlCommand();
private SqlTransaction DbTran;
private string strConnString = ConfigurationManager.ConnectionStrings["WebsiteConnectionString"].ToString();

public void setConnString(string strConn)
{
try
{
strConnString = strConn;
}
catch (Exception exp)
{
throw exp;
}
}

public string getConnString()
{
try
{
return strConnString;
}
catch (Exception exp)
{
throw exp;
}
}

private void createConn()
{
try
{

DbConn.ConnectionString = strConnString;
DbConn.Open();

}
catch (Exception exp)
{
throw exp;
}
}
public void closeConnection()
{
try
{
if (DbConn.State != 0)
DbConn.Close();
}
catch (Exception exp)
{
throw exp;
}
}

public void beginTrans()
{
try
{
if (DbTran == null)
{
if (DbConn.State == 0)
{
createConn();
}

DbTran = DbConn.BeginTransaction();
DbCommand.Transaction = DbTran;
DbAdapter.SelectCommand.Transaction = DbTran;
DbAdapter.InsertCommand.Transaction = DbTran;
DbAdapter.UpdateCommand.Transaction = DbTran;
DbAdapter.DeleteCommand.Transaction = DbTran;

}

}
catch (Exception exp)
{
throw exp;
}
}
public void commitTrans()
{
try
{
if (DbTran != null)
{
DbTran.Commit();
DbTran = null;
}

}
catch (Exception exp)
{
throw exp;
}
}
public void rollbackTrans()
{
try
{
if (DbTran != null)
{
DbTran.Rollback();
DbTran = null;
}

}
catch (Exception exp)
{
throw exp;
}
}

/// <summary>
/// Fills the Dataset dset and its Table tblname via stored procedure provided as spName arguement.Takes Parameters as param
/// </summary>
/// <param name="dSet"></param>
/// <param name="spName"></param>
/// <param name="param"></param>
/// <param name="tblName"></param>
public void selectStoredProcedure(DataSet dSet, string spName, Hashtable param, string tblName)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = spName;
DbCommand.CommandType = CommandType.StoredProcedure;
foreach (string para in param.Keys)
{
DbCommand.Parameters.AddWithValue(para, param[para]);

}

DbAdapter.SelectCommand = (DbCommand);
DbAdapter.Fill(dSet, tblName);
}
catch (Exception exp)
{

throw exp;
}
}

public void selectStoredProcedure(DataSet dSet, string spName, string tblName)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = spName;
DbCommand.CommandType = CommandType.StoredProcedure;
DbAdapter.SelectCommand = DbCommand;
DbAdapter.Fill(dSet, tblName);
}
catch (Exception exp)
{
throw exp;
}
}

public void selectQuery(DataSet dSet, string query, string tblName)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.CommandTimeout = 600;
DbCommand.Connection = DbConn;
DbCommand.CommandText = query;
DbCommand.CommandType = CommandType.Text;
DbAdapter = new SqlDataAdapter(DbCommand);
DbAdapter.Fill(dSet, tblName);
}
catch (Exception exp)
{
DbAdapter.Dispose();
DbConn.Close();
throw exp;
}
finally
{
DbAdapter.Dispose();
DbConn.Close();
}
}

public int executeQuery(string query)
{
try
{

if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = query;
DbCommand.CommandType = CommandType.Text;
return DbCommand.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
}
finally
{
DbAdapter.Dispose();
DbConn.Close();
}
}
public int executeStoredProcedure(string spName, Hashtable param)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = spName;
DbCommand.CommandType = CommandType.StoredProcedure;
foreach (string para in param.Keys)
{
DbCommand.Parameters.AddWithValue(para, param[para]);
}
return DbCommand.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
}
}
public int returnint32(string strSql)
{
try
{
if (DbConn.State == 0)
{

createConn();
}
else
{
DbConn.Close();
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = strSql;
DbCommand.CommandType = CommandType.Text;
return (int)DbCommand.ExecuteScalar();
}
catch (Exception exp)
{
return 0;
}
}
public Int64 returnint64(string strSql)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.Connection = DbConn;
DbCommand.CommandText = strSql;
DbCommand.CommandType = CommandType.Text;
return (Int64)DbCommand.ExecuteScalar();
}
catch (Exception exp)
{
throw exp;
}
}
public int executeDataSet(DataSet dSet, string tblName, string strSql)
{
try
{
if (DbConn.State == 0)
{
createConn();
}

DbAdapter.SelectCommand.CommandText = strSql;
DbAdapter.SelectCommand.CommandType = CommandType.Text;
SqlCommandBuilder DbCommandBuilder = new SqlCommandBuilder(DbAdapter);

return DbAdapter.Update(dSet, tblName);
}
catch (Exception exp)
{
throw exp;
}
}

public bool checkDbConnection()
{
int _flag = 0;
try
{
if (DbConn.State == ConnectionState.Open)
{
DbConn.Close();
}

DbConn.ConnectionString = getConnString();
DbConn.Open();
_flag = 1;
}
catch (Exception ex)
{
_flag = 0;
}
if (_flag == 1)
{
DbConn.Close();
_flag = 0;
return true;
}
else
{
return false;
}

}
public string GetColumnValue(string Query)
{
try
{
if (DbConn.State == 0)
{
createConn();
}
DbCommand.CommandTimeout = 120;
DbCommand.Connection = DbConn;
DbCommand.CommandType = CommandType.Text;
DbCommand.CommandText = Query;

object objResult = DbCommand.ExecuteScalar();
if (objResult == null)
{
return "";
}
if (objResult == System.DBNull.Value)
{
return "";
}
else
{
return Convert.ToString(objResult);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbAdapter.Dispose();
DbConn.Close();
}
}
}
}

I will not go into any detail of the code written in DbAccess.cs file but I will tell you three main things about my DbAccess.cs file 1)  I have created a namespace DataAccessLayer and place the DbAccess class inside the namespace. Namespaces are a way to define the classes and other types of data into one hierarchical structure. System is the basic namespace used by every .NET page. A namespace can be created via the Namespace keyword just like I did. 2) private string strConnString = ConfigurationManager.ConnectionStrings[“WebsiteConnectionString”].ToString() contains the name of the connection string(WebsiteConnectionString) that I declared in web.config file. 3) DbAccess class contains all the methods to communicate with database via query and store procedures. It contains all the methods for you to perform the select, insert, update and delete the data. Now open your BusComments.cs file and clear it by deleting all the built-in code and then copy/paste the below mention code in it. BusComments.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using DataAccessLayer;
  7. namespace BusinessLayer
  8. {
  9. public class BusComments
  10. {
  11. DbAccess _dbAccess = new DbAccess();
  12. private DataSet _CommentsDS = new DataSet();
  13. public DataSet CommentsDS
  14. {
  15. get
  16. {
  17. return _CommentsDS;
  18. }
  19. set
  20. {
  21. _CommentsDS = value;
  22. }
  23. }
  24. public void getComments()
  25. {
  26. try
  27. {
  28. string strSQL = “SELECT * from comments”;
  29. //Creating Datatable, if datatable not exist already.
  30. //The data return by query will be stored in DataTable.
  31. if (_CommentsDS.Tables.Contains(“GetComments”))
  32. {
  33. _CommentsDS.Tables.Remove(“GetComments”);
  34. }
  35. _dbAccess.selectQuery(_CommentsDS, strSQL, “GetComments”);
  36. }
  37. catch (Exception ex)
  38. {
  39. throw ex;
  40. }
  41. }
  42. }
  43. }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DataAccessLayer;

namespace BusinessLayer
{
public class BusComments
{
DbAccess _dbAccess = new DbAccess();
private DataSet _CommentsDS = new DataSet();
public DataSet CommentsDS
{
get
{
return _CommentsDS;
}
set
{
_CommentsDS = value;
}
}

public void getComments()
{
try
{
string strSQL = "SELECT * from comments";
//Creating Datatable, if datatable not exist already.
//The data return by query will be stored in DataTable.
if (_CommentsDS.Tables.Contains("GetComments"))
{
_CommentsDS.Tables.Remove("GetComments");
}

_dbAccess.selectQuery(_CommentsDS, strSQL, "GetComments");

}
catch (Exception ex)
{
throw ex;
}
}
}
}

Same as DbAccess.cs, I have created a namespace BusinessLayer and put BusComments class in it. I have declared a private dataset _CommentsDS and define a public dataset _CommentsDS in BusComments class. After interacting with database, Private Dataset will return all the data to the public dataset so that data can be accessible to the Presentation Layer. You may notice that I have used the DataAccessLayer namespace with other namespaces. I have also created the object of DbAccess class to get the appropriate methods written inside it to communicate with database; it’s all possible due to the inclusion of DataAccessLayer namespace. So don’t forget to include DataAccessLayer namespace in your every business layer class. Now open the Default.aspx file and again clear all the pre written code in it and then copy/paste the following code in it. Default.aspx

  1. <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”Default” %>
  2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
  3. <html xmlns=”http://www.w3.org/1999/xhtml”&gt;
  4. <head runat=”server”>
  5. <title>Designing and implementing the 3-tier architecture in asp.net</title>
  6. <style type=”text/css”>
  7. .textDIV
  8. {
  9. font-family: Verdana;
  10. font-size: 12px;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <form id=”form1″ runat=”server”>
  16. <div class=”textDIV”>
  17. <table width=”100%” border=”0″ cellpadding=”0″ cellspacing=”0″ align=”center”>
  18. <tr>
  19. <td style=”width: 45%”>
  20. </td>
  21. <td>
  22. </td>
  23. <td>
  24. </td>
  25. </tr>
  26. <tr>
  27. <td width=”20%” colspan=”3″ align=”center”>
  28. <span style=”display: inline;”><strong>Comments</strong></span>
  29. </td>
  30. </tr>
  31. <tr>
  32. <td width=”20%” colspan=”3″>
  33. </td>
  34. </tr>
  35. <tr>
  36. <td colspan=”3″ align=”center”>
  37. <hr style=”width: 50%;” />
  38. </td>
  39. </tr>
  40. <tr>
  41. <td>
  42. </td>
  43. </tr>
  44. <tr>
  45. <td align=”center” width=”100%”>
  46. <asp:GridView ID=”GridView1″ runat=”server” EnableTheming=”false” AutoGenerateColumns=”false”
  47. GridLines=”None” OnRowDataBound=”GridView1_RowDataBound” Width=”660px” HorizontalAlign=”Center”>
  48. <Columns>
  49. <asp:TemplateField HeaderText=”Sr No” HeaderStyle-Width=”15%” HeaderStyle-HorizontalAlign=”Center”>
  50. <ItemTemplate>
  51. <%# Container.DataItemIndex + 1 %>
  52. </ItemTemplate>
  53. <ItemStyle HorizontalAlign=”Center” />
  54. </asp:TemplateField>
  55. <asp:TemplateField HeaderText=”First Name” HeaderStyle-Width=”15%” HeaderStyle-HorizontalAlign=”Left”>
  56. <ItemTemplate>
  57. <asp:Label ID=”lblFirstName” runat=”server” EnableTheming=”false” Text='<%# Bind(“first_name”)%>’></asp:Label>
  58. </ItemTemplate>
  59. <ItemStyle HorizontalAlign=”Left” />
  60. </asp:TemplateField>
  61. <asp:TemplateField HeaderText=”Last Name” HeaderStyle-Width=”15%” HeaderStyle-HorizontalAlign=”Left”>
  62. <ItemTemplate>
  63. <asp:Label ID=”lblLastName” runat=”server” EnableTheming=”false” Text='<%# Bind(“last_name”)%>’></asp:Label>
  64. </ItemTemplate>
  65. <ItemStyle HorizontalAlign=”Left” />
  66. </asp:TemplateField>
  67. <asp:TemplateField HeaderText=”Comments” HeaderStyle-Width=”50%” HeaderStyle-HorizontalAlign=”Left”>
  68. <ItemTemplate>
  69. <asp:Label ID=”lblComments” runat=”server” EnableTheming=”false” Text='<%# Bind(“comments”)%>’></asp:Label>
  70. </ItemTemplate>
  71. <ItemStyle HorizontalAlign=”Left” />
  72. </asp:TemplateField>
  73. </Columns>
  74. </asp:GridView>
  75. </td>
  76. </tr>
  77. <tr>
  78. <td>
  79. </td>
  80. </tr>
  81. <tr>
  82. <td align=”center”>
  83. <input type=”button” value=”Back” onclick=”history.back(-1);” />
  84. </td>
  85. </tr>
  86. </table>
  87. </div>
  88. </form>
  89. </body>
  90. </html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!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>Designing and implementing the 3-tier architecture in asp.net</title>
<style type="text/css">
.textDIV
{
font-family: Verdana;
font-size: 12px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td style="width: 45%">

</td>
<td>

</td>
<td>

</td>
</tr>
<tr>
<td width="20%" colspan="3" align="center">
<span style="display: inline;"><strong>Comments</strong></span>
</td>
</tr>
<tr>
<td width="20%" colspan="3">

</td>
</tr>
<tr>
<td colspan="3" align="center">
<hr style="width: 50%;" />
</td>
</tr>
<tr>
<td>

</td>
</tr>
<tr>
<td align="center" width="100%">
<asp:GridView ID="GridView1" runat="server" EnableTheming="false" AutoGenerateColumns="false"
GridLines="None" OnRowDataBound="GridView1_RowDataBound" Width="660px" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Sr No" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" EnableTheming="false" Text='<%# Bind("first_name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" HeaderStyle-Width="15%" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" EnableTheming="false" Text='<%# Bind("last_name")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments" HeaderStyle-Width="50%" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server" EnableTheming="false" Text='<%# Bind("comments")%>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>

</td>
</tr>
<tr>
<td align="center">
<input type="button" value="Back" onclick="history.back(-1);" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

As you have seen that in .aspx file I just placed the asp:GridView control. Now let’s have a look over the Default.aspx.cs file Default.aspx.cs

  1. using System;
  2. using System.Collections;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Security;
  8. using System.Web.UI;
  9. using System.Web.UI.HtmlControls;
  10. using System.Web.UI.WebControls;
  11. using System.Web.UI.WebControls.WebParts;
  12. using System.Xml.Linq;
  13. using BusinessLayer;
  14. public partial class Default : System.Web.UI.Page
  15. {
  16. BusComments _objComments = new BusComments();
  17. protected void Page_Load(object sender, EventArgs e)
  18. {
  19. if (!Page.IsPostBack)
  20. {
  21. BindGrid();
  22. }
  23. }
  24. public void BindGrid()
  25. {
  26. _objComments.getComments();
  27. //Tables[“GetComments”] is the DataTable that we have created in BusComments class
  28. GridView1.DataSource = _objComments.CommentsDS.Tables[“GetComments”];
  29. GridView1.DataBind();
  30. }
  31. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  32. {
  33. if (e.Row.RowType == DataControlRowType.DataRow)
  34. {
  35. ((Label)e.Row.FindControl(“lblComments”)).Text = ((Label)e.Row.FindControl(“lblComments”)).Text.ToString().ToUpper();
  36. }
  37. }
  38. }
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BusinessLayer;

public partial class Default : System.Web.UI.Page
{
BusComments _objComments = new BusComments();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}

public void BindGrid()
{
_objComments.getComments();
//Tables[“GetComments”] is the DataTable that we have created in BusComments class
GridView1.DataSource = _objComments.CommentsDS.Tables["GetComments"];
GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((Label)e.Row.FindControl("lblComments")).Text = ((Label)e.Row.FindControl("lblComments")).Text.ToString().ToUpper();
}

}
}

I have included the BusinessLayer namespace on the top so that I can get access to the BusComments class. Then I initialized the object of BusComments class and then by using the object I have called my required function placed in BusComments class to get data and populate the GridView. Now you have seen I called the function written in BusComments class to get the data from database and that function actually called its required function written in DbAccess class to get the data from database. DbAccess gets the data from database and return to BusComments Class, BusComments class gets the data from DbAccess class and return to Presentation Layer which is default.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s