Advanced application of entity classes in Windows programs--------------------the state of mind is a realm.

Source: Internet
Author: User

First, the business

We have learned this in a more or less understanding of the business. I have a deeper understanding of the business today. For me, I would like to share with you.

Resolution: 1.ADO. NET provides transaction processing capabilities

Open transaction in 2.c#

3. We don't have to open a transaction in our SQL background.

4.eg. I'm going to add grade on the Frmsw form, we first set a unique constraint in the database for its gradename in the grade table, and if the gradename repeats, the transaction rolls it back, such as Gradename does not repeat.

String str = "Data source=.;            Initial catalog=myschool;uid=sa;pwd=1 ";            SqlConnection con = new SqlConnection (str);            String sql = "INSERT into grade values (@gname)";            SqlParameter para = new SqlParameter ("@gname", txtName.Text);            SqlCommand cmd = new SqlCommand (sql, con); 1.0 The Connection object must be con.begintransaction sqltransaction Tran = con After the connection is opened.            BeginTransaction (); Cmd.            Parameters.Add (para); Con.            Open (); 1.1 The transaction property of the transaction object and CMD will be built through con to bind the cmd.                Transaction = Tran;            The initial value to int count = 0; try {count = cmd.                ExecuteNonQuery ();            1.3 Commit Transaction Tran.commit (); } catch (Exception ex) {//1.4 rolls back the transaction tran.                Rollback (); MessageBox.Show (ex.            Message); } if (Count > 0) {messagebox.sHow ("Add success!            "); } con. Close ();

Knowledge------------------"We want to see if it repeats when we break the breakpoint. We write the following code in the database:

    

SELECT * from Grade with (NOLOCK)

Second, the Msgdiv component explanation.

The 1.Msgdiv class is as follows

Using system;using system.collections.generic;using system.text;using system.windows.forms;///<summary>///    Message Bar callback function delegate///</summary>public delegate void Dgmsgdiv (); <summary>///News bar class with Timer///</summary>public class msgdiv:system.windows.forms.label{Priva    Te Timer timerlable = new timer ();    <summary>///Message Callback delegate object///</summary> private dgmsgdiv dgcallback = null; #region Timer///<summary>///timer timermsg {get {return ti merlable;    } set {timerlable = value;} } #endregion #region Msgdiv constructor///<summary>//Msgdiv constructor///</summary> public Msgdiv (    ) {Initallmsgdiv (7, 7); }///<summary>//Msgdiv constructors///</summary>//<param name= "x" > positioning x Axis coordinates </param>// /<param name= "y" > Position y-axis coordinates </param> public msgdiv (int x, int y) {initallmsgdiv (x, y); #endregion #region Initialize the message Bar///<summary>//Initialize the message Bar///</summary> private void initallmsg DIV (int x, int y) {this.        AutoSize = true; This.        BackColor = System.Drawing.Color.FromArgb (((int) ((byte) (255))), ((int) (((byte) (255))), ((int) (((Byte) (192))); This.        BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; This.        ContextMenuStrip = this.cmslist; This. Font = new System.Drawing.Font ("Arial", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((Byte) (        134))); This.        ForeColor = System.Drawing.Color.Red; This.        Location = new System.Drawing.Point (x, y); This.        MaximumSize = new System.Drawing.Size (980, 525); This.        Name = "Msgdiv"; This.        Padding = new System.Windows.Forms.Padding (7); This.        Size = new System.Drawing.Size (71, 31); This.        TabIndex = 1; This.        Text = "Message Bar"; This.        Visible = false; Adds an event this to the delegate. DoubleClick + = new SYstem.        EventHandler (This.msgdiv_doubleclick); This.        MouseLeave + = new System.EventHandler (this.msgdiv_mouseleave); This.        MouseHover + = new System.EventHandler (this.msgdiv_mousehover);        This.timerLable.Interval = 1000;    This.timerLable.Tick + = new System.EventHandler (This.timerlable_tick); #endregion #region Add a message bar to the specified container///<summary>///Add the message bar to the specified container form///</summary>//< param name= "form" ></param> public void Addtocontrol (Form form) {form.    Controls.Add (this); }///<summary>///Add the message bar to the specified container GroupBox//</summary>//<param name= "form" ></param&gt    ;    public void Addtocontrol (GroupBox GroupBox) {groupBox.Controls.Add (this);    }///<summary>///Add the message bar to the specified container panel///</summary>//<param name= "form" ></param> public void Addtocontrol (panel panel) {panel.    Controls.Add (this); } #endregion//---------------------------------------------------------------------------the relevant parameters #region the message were Hiddenclick,countnumber,    Constcountnumber//<summary>///How long the number of seconds is currently displayed///</summary> int hiddenclick = 0;    <summary>////How long the number of seconds to display variable parameter///</summary> int countnumber = 3;     <summary>////How long to display the number of seconds fixed parameter///</summary> int constcountnumber = 3; #endregion #region Timer displays countnumber seconds after auto-hide Div-timerlable_tick (object sender, EventArgs e) private void Timerlable_        Tick (object sender, EventArgs e) {if (Hiddenclick > CountNumber-2) {msgdivhidden ();            } else {hiddenclick++;        Remaincount (); }} #endregion #region hide the message box and stop the timer +void Msgdivhidden ()///<summary>//Hide message box and stop timing//&LT;/SU mmary> public void Msgdivhidden () {this.        Text = ""; This.        Visible = false;    This.hiddenclick = 0;    This.tslblRemainSecond.Text = "";        if (this.timerLable.Enabled = = True) this.timerLable.Stop (); Call the delegate and then empty the delegate if (Dgcallback! = null && dgcallback.getinvocationlist ().            Length > 0) {dgcallback ();        Dgcallback-= Dgcallback; }} #endregion #region display a message string in a message box +void msgdivshow (String msg)///<summary>///Display the message string in a message box/        </summary>//<param name= "MSG" > string to display </param> public void Msgdivshow (String msg) { This.        Text = msg; This.        Visible = true;        This.countnumber = constcountnumber;//default setting shows the number of seconds is 10;    This.hiddenclick = 0;//Resets the reciprocal description This.timerLable.Start (); #endregion #region Display the message string in a message box and call the callback function when the message disappears +void msgdivshow (String msg, Dgmsgdiv callback)//<summary >////The message string is displayed in a message box and the callback function is called when the message disappears///</summary>//<param name= "MSG" > The string to display </param>// /<param Name= "callback"; callback function </param> public void Msgdivshow (String msg, Dgmsgdiv callback) {msgdivshow (msg);    Dgcallback = callback;    #endregion #region The message string is displayed in a message box and the callback function is called when the specified time message disappears +void msgdivshow (string msg, int seconds, Dgmsgdiv callback) <summary>////The message string is displayed in a message box and the callback function is called when the message disappears///</summary>//<param name= "MSG" > the string to display <    /param>//<param name= "seconds" > Message display time </param>//<param Name= "callback" > Callback function </param>        public void Msgdivshow (string msg, int seconds, Dgmsgdiv callback) {Msgdivshow (msg, seconds);    Dgcallback = callback; #endregion #region Display a message string in a message box and specify the number of seconds the message box displays +void msgdivshow (string msg, int seconds)//<summary>/ Displays a message string in a message box and specifies the number of seconds the message box displays///</summary>//<param name= "MSG" > String to display </param>//<param N Ame= "Seconds" > message box shows the number of seconds </param> public void Msgdivshow (string msg, int seconds) {this. Text = msg; This.        Visible = true;        This.countnumber = seconds;    This.hiddenclick = 0;//Resets the reciprocal description This.timerLable.Start (); } #endregion//---------------------------------------------------------------------------#region Events ~~~! Msgdiv_mousehover,msgdiv_mouseleave,msgdiv_doubleclick//Stop time when the mouse rests on the div private void Msgdiv_mousehover (object send    Er, EventArgs e) {if (this.timerLable.Enabled = = True) this.timerLable.Stop (); }//When the mouse moves away from the Div, continue in time private void Msgdiv_mouseleave (object sender, EventArgs e) {//When the message box is being displayed, the reply box is not displayed, the timer is stopping , restart the timer if (this.    Visible = = True && this.timerLable.Enabled = = False) This.timerLable.Start ();    }//Double-click the message box to close the message box private void Msgdiv_doubleclick (object sender, EventArgs e) {Msgdivhidden (); } #endregion}

2. We want to put the type in the application form, in order to make it easier for everyone to find later, we should put it in a new folder to put this class in.

3. We will find this control in the tool class —————————— "is the control generated by your class

4. We add its form to the label control to modify it to "hehe", but it's not as rigid as it looks, so the controls we just built are gorgeous. We can also change the number of seconds.

private void Form1_Load (object sender, EventArgs e)        {            msgdiv1.msgdivshow ("hehe", 3, Test);            Mytool tool = new Mytool ();            list<grade> list = tool. datatabletolist<grade> (DT);        }        public void Test ()        {            MessageBox.Show ("Test");        }

This is the end of this control, there is no very magical ********

Third, the use of datatabletolist

1. Place the Mytool class on the Myschool.dal layer

Using system;using system.collections.generic;using system.data;using system.data.sqlclient;using System.Linq;using        System.reflection;using system.text;using system.threading.tasks;namespace myschool.dal{public class MyTool { <summary>//datasettolist//</summary>/<typeparam name= "T" > Conversion type </ty peparam>//<param name= "DataSet" > Data source </param>//<param name= "Tableindex" > Indexes requiring conversion tables &LT         ;/param>//<returns></returns> public ilist<t> datatabletolist<t> (DataTable DT)            {//Confirm parameter valid if (dt = = NULL) return null;            list<t> list = new list<t> (); for (int i = 0; i < dt. Rows.Count;                i++) {//Create generic object T _t = activator.createinstance<t> (); Gets all properties of the object propertyinfo[] PropertyInfo = _t.gettype ().       GetProperties ();         for (int j = 0; j < dt. Columns.count;                        J + +) {foreach (PropertyInfo info in PropertyInfo) { The property name and column name are assigned the same value if (dt. COLUMNS[J]. Columnname.toupper (). Equals (info. Name.toupper ())) {if (dt). ROWS[I][J]! = DBNull.Value) {info. SetValue (_t, dt.                            ROWS[I][J], NULL); } else {info.                            SetValue (_t, NULL, NULL);                        } break; }}} list.            ADD (_t);        } return list; }    }}

In the Myschool.dal layer ———————— "This class replaces the foreach

Public list<grade> loadallgradetolist ()        {           //list<grade> List = new list<grade> ();            String sql = "SELECT * from grade";            DataTable dt = sqlhelper.executedatatable (SQL);
Instead of foreach
Mytool tool=new Mytool (); List<grade> List=tool. datatabletolist<grade> (DT); Turn DT into list<student> //foreach (DataRow row in dt. Rows) //{//// each row represents a row in the table so one row corresponds to a Grade object // Grade Grade = new Grade (); grade. Gradeid = Convert.ToInt32 (row["Gradeid"]); grade. Gradename = row["Gradename"]. ToString (); list. ADD (grade); } return list; }

Four, multi-table data binding to the same DataGridView

Issue: Show student name Account name score

Parsing: Creating a new entity class in an entity class Studentextends:student account name, score
In the DAL layer, create a class named Studentdal that defines a method in this class Loadstudentinfo () returns a value type List<studentextends>
Method of invoking Dal at the BLL layer
Gets the generic collection returned to the BLL after the UI layer
To use generics as a data source for DGV

public class Studentextends:student    {       //One is the account name public       string Subjectname {get; set;}       Test time public       DateTime examdate {get; set;}       Result public       int Studentresult {get; set;}    }

  

Public list<studentextends> Loadstudentinfo () {list<studentextends> list=new List<StudentE           Xtends> ();                          String sql = @ "Select Studentname,subjectname,studentresult,examdate from Student,subject,result where Student.studentno=result.studentno and result.subjectid=subject.su           Bjectid ";           DataTable dt=sqlhelper.executedatatable (SQL); foreach (DataRow item in DT. Rows) {//an item is a record in a table (student name, account name, score and time)//A free student object Studentexten                DS stu=new studentextends (); Stu. Studentname = item["Studentname"].                ToString (); Stu. Subjectname = item["Subjectname"].                ToString (); Stu.                Studentresult = Convert.ToInt32 (item["Studentresult"]); Stu.               Examdate = Convert.todatetime (item["examdate"]); List.           ADD (Stu);       } return list; }

  

Public list<studentextends> Loadstudentinfo ()      {         return DAL. Loadstudentinfo ();      }

  

private void Frmselectresult_load (object sender, EventArgs e)        {          list<studentextends> list=  BLL. Loadstudentinfo ();            Dgvresult.datasource = list;        }

  

 

Advanced application of entity classes in Windows programs--------------------the state of mind is a realm.

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.