3-layer structure (2)

Source: Internet
Author: User

We have introduced the three-tier structure. Next we will see how it works in the application:

Before that, we should create a database in the database and add tables.

When creating these projects, we need to add references to all the items first, just add project references directly.

Entity class: You can add entity classes for multiple tables. Here we are doing

Create an object class for ease of use. You only need to create an object class object, and you can use its attributes and assign values.

// Apply [Serializable] to facilitate serialization // publish the object class, so that public class Depart {int departId; public int DepartId {get {return departId;} can be used later ;} set {departId = value ;}} string partition name; public string partition name {get {return partition name ;}set {partition name = value ;}}}

[Serializable]public class ClassInfo{int classId;public int ClassId{get { return classId; }set { classId = value; }}string className;public string ClassName{get { return className; }set { className = value; }}int departId;public int DepartId{get { return departId; }set { departId = value; }}}

SQLServerDAL data access layer ):

1) Generic database category

Namespace SQLServerDAL {// generic Database Connector class. Without an access modifier, it indicates that it can only be used by the current project class DBHelper {// connection string connString = "server =. \ sqlexpress; database = SchoolDB2; uid = sa; pwd = 199298 "; // connect to the database. This method can be used to execute the add, delete, and modify command public int ExecuteNonQuary (string SQL, sqlParameter [] ps) {SqlConnection conn = new SqlConnection (connString); SqlCommand cmd = conn. createCommand (); cmd. commandText = SQL; cmd. parameters. addRange (ps); conn. open (); int x = cmd. executeNonQuery (); conn. close (); return x;} // connect to the database and run the query command public DataTable GetData (string SQL, SqlParameter [] ps) {SqlConnection conn = new SqlConnection (connString ); sqlCommand cmd = conn. createCommand (); cmd. commandText = SQL; cmd. parameters. addRange (ps); SqlDataAdapter da = new SqlDataAdapter (cmd); DataTable dt = new DataTable (); da. fill (dt); return dt ;}}}

2) specific database category:

Departs table access:

Public class Internal Service {// object of the generic database internal class. All methods in the class can access DBHelper db = new DBHelper (); // Add the public void AddDepart (Depart depart) {string SQL = "Insert Into Depart (partition name) Values (@ partition name )"; sqlParameter [] ps = new SqlParameter [] {new SqlParameter ("@ parameter name", depart. commonName)}; // call the addition, deletion, and modification methods in the generic database sequence class to add a database. executeNonQuary (SQL, ps);} // change the public void UpdateDepart (Depart depart) {string SQL = "Update Depart set Partition name = @ partition name where departId = @ departId "; sqlParameter [] ps = new SqlParameter [] {new SqlParameter ("@ parameter name", depart. parameter Name), new SqlParameter ("@ DepartId", depart. departId)}; db. executeNonQuary (SQL, ps);} // Delete the public void DeleteDepartById (int departId) {string SQL = "Delete from Depart where departId = @ departId "; sqlParameter [] ps = new SqlParameter [] {new SqlParameter ("@ departId", departId)}; db. executeNonQuary (SQL, ps);} // query the public Depart SelectDepartById (int departId) {string SQL = "Select * from Depart where departId = @ departId "; sqlParameter [] ps = new SqlParameter [] {new SqlParameter ("@ departId", departId)}; DataTable dt = db. getData (SQL, ps); // if (dt. rows. count = 0) {return null;} // send the data row DataRow dr = dt. rows [0]; // The physical class objects of the seat and the value of Depart depart = new Depart (); depart. departId = (int) dr ["departId"]; depart. commonName = (string) dr ["CommonName"]; // returns the object return depart;} // queries all records in the database public List <Depart> SelectDepart () {string SQL = "Select * from Depart"; SqlParameter [] ps = new SqlParameter [] {}; DataTable dt = db. getData (SQL, ps); List <Depart> list = new List <Depart> (); foreach (DataRow dr in dt. rows) {Depart depart = new Depart (); depart. departId = (int) dr ["departId"]; depart. counter name = (string) dr ["counter name"]; list. add (depart) ;}return list ;}}

Classes table access:

public class ClassInfoService{DBHelper db = new DBHelper();public void AddClassInfo(ClassInfo classInfo){string sql = "Insert Into Classes(className, departId)Values(@className, @departId)";SqlParameter[] ps = new SqlParameter[] {new SqlParameter("@ClassName",classInfo.ClassName),new SqlParameter("@DepartId",classInfo.DepartId),};db.ExecuteNonQuary(sql, ps);}public void UpdateClassInfo(ClassInfo classInfo){string sql = "Update  Classes set className=@className,departId=@ departId where classId=@classId";SqlParameter[] ps = new SqlParameter[] {new SqlParameter("@ClassName",classInfo.ClassName),new SqlParameter("@DepartId",classInfo.DepartId)};db.ExecuteNonQuary(sql, ps);}public void DeleteClassInfoById(int classId){string sql = "Delete  from Classes where classId=@classId";SqlParameter[] ps = new SqlParameter[] {new SqlParameter("@classId",classId)};db.ExecuteNonQuary(sql, ps);}public ClassInfo SelectClassInfoById(int classId){string sql = "Select * from Classes where classId=@classId";SqlParameter[] ps = new SqlParameter[] {new SqlParameter("@classId",classId)};DataTable dt = db.GetData(sql, ps);if (dt.Rows.Count == 0){return null;}DataRow dr = dt.Rows[0];ClassInfo classInfo = new ClassInfo();classInfo.ClassId = (int)dr["classId"];classInfo.ClassName = (string)dr["className"];classInfo.DepartId = (int)dr["departId"];return classInfo;}public List<ClassInfo> SelectClassInfo(){string sql = "Select * from Classes";SqlParameter[] ps = new SqlParameter[] { };DataTable dt = db.GetData(sql, ps);List<ClassInfo> list = new List<ClassInfo>();foreach (DataRow dr in dt.Rows){ClassInfo classInfo = new ClassInfo();classInfo.ClassId = (int)dr["classId"];classInfo.ClassName = (string)dr["className"];classInfo.DepartId = (int)dr["departId"];list.Add(classInfo);}return list;}public List<ClassInfo> SelectClassInfoByDepartId(int departId){string sql = "Select * from Classes where departId=@departId";SqlParameter[] ps = new SqlParameter[] {new SqlParameter("@departId",departId)};DataTable dt = db.GetData(sql, ps);List<ClassInfo> list = new List<ClassInfo>();foreach (DataRow dr in dt.Rows){ClassInfo classInfo = new ClassInfo();classInfo.ClassId = (int)dr["classId"];classInfo.ClassName = (string)dr["className"];classInfo.DepartId = (int)dr["departId"];list.Add(classInfo);}return list;}}

BLL business logic layer ):

Now we only make calls. As we learn, we will gradually improve the content, not just the call.

Business logic layer of the Departs table:

Public class volume manager {// make a static volume service object static volume service ds = new volume service (); // call the public static void AddDepart (Depart depart) {ds. addDepart (depart);} public static void UpdateDepart (Depart depart) {ds. updateDepart (depart);} public static void DeleteDepartById (int departId) {ds. deleteDepartById (departId);} public static Depart SelectDepartById (int departId) {return ds. selectDepartById (departId);} public static List <Depart> SelectDepart () {return ds. selectDepart ();}}

Business logic layer of the Classes table:

public class ClassInfoManager{static ClassInfoService cs = new ClassInfoService();public static void AddClassInfo(ClassInfo classInfo){cs.AddClassInfo(classInfo);}public static void UpdateClassInfo(ClassInfo classInfo){cs.UpdateClassInfo(classInfo);}public static void DeleteClassInfoById(int classId){cs.DeleteClassInfoById(classId);}public static ClassInfo SelectClassInfoById(int classId){return cs.SelectClassInfoById(classId);}public static List<ClassInfo> SelectClassInfo(){return cs.SelectClassInfo();}public static List<ClassInfo> SelectClassInfoByDepartId(int departId){return cs.SelectClassInfoByDepartId(departId);}}

Finally, the data presentation layer:

Here, we need to display the information in the database table to the form through the form loading event, and then use the buttons on the form to add, delete, and modify.

Form Design in the main form:

650) this. width = 650; "title =" Capture 5.PNG" src = "http://www.bkjia.com/uploads/allimg/131228/1923451123-0.png" alt = "125240108.png"/>

Check how the program in the main form is written:

Public frmMain () {InitializeComponent () ;}// private void button1_Click (object sender, EventArgs e) {// create a frmDepart object frmDepart fd = new frmDepart (); // display it to fd. showDialog ();} private void button2_Click (object sender, EventArgs e) {// create a frmClasses object frmClasses fc = new frmClasses (); // display it to fc. showDialog ();}

Let's take a look at the design of the frmDepart form:

650) this. width = 650; "title =" Capture 6.PNG" src = "http://www.bkjia.com/uploads/allimg/131228/1923454162-1.png" alt = "125649861.png"/>

Let's take a look at the functions of the buttons on the form:

Public partial class frmDepart: Form {public frmDepart () {InitializeComponent ();} private void frmDepart_Load (object sender, EventArgs e) {// fill control FillListView ();} private void FillListView () {// clear the control this. listDepart. items. clear (); // call the business method to display the data to the List Control List <Depart> departs = Volume Manager. selectDepart (); // make each piece of data into a list item and add it to the list to foreach (Depart depart in departs) {ListViewItem lvi = new ListViewItem (); lvi. text = Depart. departId. toString (); lvi. subItems. add (depart. registrant name); // set the Tag attribute in the list to a school object lvi. tag = depart; this. listDepart. items. add (lvi) ;}/// set the edit status variable to bool eidtFalg = false; /// <summary> /// Add button to clear the content in the input box, and set the editing status to add /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void btnAdd_Click (object sender, eventArgs e) {// Add button // clear the content in the input box // set the editing status to add // initialize InitInputControl (); // set the editing status Status: New eidtFalg = false;} // initialization method private void InitInputControl () {// convert the content in the input box to this.txt DepartId. text = "" Maid name. text = "";} // set the global variable int departId = 0; private void bnSave_Click (object sender, EventArgs e) {// Save button // first determine whether the editing status is new or edit. // determine the method to be called Based on the editing status. // after saving, set the editing status to add/clear the input box // first, set the value to int departId = int.Parse(this.txt DepartId. text); string parameter name = this.txt parameter name. text; // convert the obtained value into an object Depar T depart = new Depart (); depart. DepartId = departId; depart. Partition name = partition name; // determine the editing status if (! EidtFalg) {// to add, call the method BLL for adding objects. manager. addDepart (depart);} else {// for editing, call the method BLL to modify the object. manager. updateDepart (depart);} // clear InitInputControl () in the input box; // set the editing status to add eidtFalg = false; // fill list control FillListView ();} /// <summary> /// delete button /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private void btnDelete_Click (object sender, eventArgs e) {// first check whether a row in ListView is selected // obtain the value of the primary key in this row // pass the value to the deleteer Method // check whether a row in ListView is selected if (this. listDepart. selectedItems. count = 0) {return;} // If a row is selected, a prompt box is displayed, asking whether you really want to delete the selected record DialogResult dr = MessageBox. show ("are you sure you want to delete it? "," Prompt box ", MessageBoxButtons. yesNo, MessageBoxIcon. question, MessageBoxDefaultButton. button2); // if (dr = DialogResult. no) {return;} // when Yes is selected, the selected row of records is made into an object, object obj = this. listDepart. selectedItems [0]. tag; Depart depart = obj as Depart; // call the SelectClassInfoByDepartId method to check whether the primary key of the selected row of records is referenced in the List in the Classes table <ClassInfo> classInfos = BLL. classInfoManager. selectClassInfoByDepartId (depart. departId); // If If (classInfos. Count! = 0) {MessageBox. show ("this record is referenced later and cannot be deleted", "prompt", MessageBoxButtons. OK, MessageBoxIcon. information); return;} // if the number of query results is 0, the deleted method is called to delete this row of records BLL based on the primary key. manager. deleteDepartById (depart. departId); // fill in the ListView control FillListView ();} private void listDepart_DoubleClick (object sender, EventArgs e) {// first check whether a row is selected in ListView // set the editing status to edit // display the data in the selected row in the input box if (this. listDepart. selectedItems. count = 0) {return;} // set the editing status to edit eidtFalg = true; // make the selected row of records into an object obj = this. listDepart. selectedItems [0]. tag; Depart depart = obj as Depart; // display the value of the selected record to this.txt DepartId in the input box. text = maid name. text = depart. partition name; // the value of this global variable is equal to the object's primary key departId = depart. departId;} // closes the private void btnCancel_Click (object sender, EventArgs e) {this. close ();}}

View the execution result:

650) this. width = 650; "title =" Capture 8.PNG" src = "http://www.bkjia.com/uploads/allimg/131228/192345EG-2.png" alt = "131357733.png"/>

The routines in the next section are the same. In this way, we have mastered the writing of the various functions, and the next section can be easily written. Come on !!!

In the future, there will also be three-layer structure upgrade practices. We will make this process clearer and clearer, so that future maintenance work will be as simple and convenient as possible.

This article from the "Lanting drunk beauty" blog, please be sure to keep this source http://7607889.blog.51cto.com/7597889/1304765

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.