C # Write a third-party control that implements a key assignment for a form control

Source: Internet
Author: User

Reason

In writing the program, often write the above code, the results of the query to display on the form, how do we do? It is the most boring and error-prone code to write one line at a given value. Have you found that the above code is doing the same thing-assignment. Similar code written more than three times, it is necessary to consider whether the process can be encapsulated. Encapsulates a method that helps us automate these repetitive operations.

thinking process

Similar methods have been written in the project in contact. It's just that it involves a lot of other methods, one set, and it's especially inconvenient to pull out. And there are a few unpleasant places: first, the control must be named the same as the corresponding entity property. For example, the name of this item, the attribute name of the entity is sname, then the control must also be sname, which is obviously contrary to the general naming convention we follow. The second is that the visibility level of the control must be set to public, otherwise it will not be assigned a value.

So, after studying his method, it was re-written and some improvements were made. Make up the above two shortcomings, make it more convenient to use.

The method used is mentioned in the title. Write a third-party control, listen to a very tall, in fact, the original C # control, to rewrite, add a self-used properties. The added property here I named it DataField, which is used to save the name of the database field. What's the effect? Look down and you'll find out.

I wrote a demo in C # to illustrate how to write a third-party control and a key assignment for a form.

Specific implementation process

Create a new C # project

Add an interface Interface1:

<span style= "FONT-SIZE:18PX;" >    interface Interface1    {       //define DataField property        string DataField {get; set;}    } </span>

Add two classes of Comboxex,comboxex:

Using System.Windows.Forms;  Add Reference    internal class Textboxex:textbox, Interface1    {       //This class inherits TextBox controls and interfaces Interface1        #region Interface1 member Public        string DataField        {get; set;}        #endregion    }    internal class Comboxex:combobox, Interface1    {        #region Interface1 member        public String DataField        {get; set;}        #endregion    }

Then open the toolbox and we'll see:

This is the third-party control we encapsulate. Drag it onto the form, right-click to view its properties

It's got one more piece. DataField property, we can assign a value to him. SID (Student table field name-study number) also drag and drop several controls and assign values.

then start writing the code formally, adding an entity class stuentity :

Note: The name of the entity attribute should be consistent with the database field name!

    public class Stuentity {//<summary>/////        </summary> public        string SID {get; Set }///<summary>//Name:///        </summary> public        string sname {get; set;}        <summary>//gender////        </summary> public        string Sex {get; set;}        <summary>///department///        </summary> Public        string Department {get; set;}        <summary>/////        </summary> public        string Grade {get; set;}        <summary>///class///        </summary> public        string Sclass {get; set;}    }

one point to note: It's just a small Demo did not adopt a hierarchical approach, and put all the written methods in the Frm Helper in class

    public class Frmhelper {///<summary>/////To assign the row of the DataTable to the entity class Enstudent///The room can be used here        A good way to convert a DataTable into a generic collection of entity classes, you can omit these assignments. </summary>//<param name= "Dr" >datatable line </param>//<returns> return entity class enstudent& lt;/returns> public static stuentity getentity (DataRow dr) {stuentity enstudent = new Stuenti            Ty (); Enstudent.sid = dr["SID"].            ToString (); Enstudent.sname = dr["Sname"].            ToString (); Enstudent.sex = dr["Sex"].            ToString (); enstudent.department = dr["department"].            ToString (); Enstudent.grade = dr["Grade"].            ToString (); Enstudent.sclass = dr["Sclass"].            ToString ();        return enstudent; }///<summary>///To populate the form's controls with the values of the attributes in the entity class//</summary>//<param name= "Enstude NT "></param> public static void Fillformbyentity (Stuentity enstudent, forM thisfrm) {//traverse the controls on the form foreach (Control ctrl in THISFRM.                    Controls) {//Inherits the interface if (Ctrl is Interface1) { Whether it belongs to the text box if (Ctrl is Textboxex) {Ctrl. Text = GetValue (Enstudent, ((TEXTBOXEX) ctrl).                    DataField); }//if it belongs to the drop-down box else if (Ctrl is Comboxex) {((COMBOXEX) ctrl). Text = GetValue (Enstudent, ((COMBOXEX) ctrl).                    DataField);                }//If there are other types of controls, you can extend them here.        }}}///<summary>///Use reflection technology to dynamically get the value corresponding to the control from the entity///</summary> <param name= "Enstudent" > Entity classes </param>//<param name= "datafiled" > Field values </param>//  <returns></returns> public static string GetValue (Stuentity enstudent, string datafiled) {          PropertyInfo field = Enstudent.gettype ().            GetProperty (datafiled); return field. GetValue (enstudent, NULL).        ToString (); }///<summary>///Execute Query statement, return a datetable///</summary>//<returns>datetab le</returns> public static DataTable QueryTable () {using (SqlConnection connection = new S Qlconnection ("server=.; Database=re_charge_sys;user id=sa;password=123456 ")) {SqlCommand cmd = connection.                CreateCommand ();                Cmd.commandtext = @ "SELECT * from student_info where SID = ' 110 '";                DataTable dt = new DataTable ();                DataSet ds = new DataSet (); try {connection.                    Open ();                    SqlDataAdapter sqladapter = new SqlDataAdapter (cmd);                    Sqladapter.fill (DS); DT = ds.                Tables[0]; } catch (System.Data.SqlClient.SqlExcEption ex) {throw new Exception (ex.                Message);            } return DT; }        }    }


Client calls:

        private void Btnfillvalue_click (object sender, EventArgs e)        {             DataTable dt = frmhelper.querytable ();            Stuentity enstudent = frmhelper.getentity (dt. Rows[0]);            Frmhelper.fillformbyentity (enstudent, this);        }        private void Form1_Load (object sender, EventArgs e)        {            cmbGrade.Items.AddRange (new string[] {"First grade", "second year", "third grade" , "Grade Four"});            CmbSex.Items.AddRange (new string[] {"Male", "female"});            CMBSEX.ITEMS.ADD (New keyvaluepair<string, string> ("male", "male"));            CMBSEX.ITEMS.ADD (New keyvaluepair<string, string> ("female", "female"));            Cmbsex.displaymember = "Key";            Cmbsex.valuemember = "Value";        }


By clicking the Assign button, the data read from the database is automatically filled into the interface controls.

Talk about third-party controls

Of course, this method can also add other properties, such as Notempty, to determine whether the empty method is written in the interface, and then let the control to inherit. The value of this property is set to True/false to determine whether the contents of the control can be empty. In this way, to avoid writing methods to judge each, save time and effort. Speaking of which I have to sigh: standing on the shoulders of giants. In fact, there are already a lot of well-packaged, powerful third-party controls on the Internet. For example, the C1studio used now, the common controls are encapsulated, adding a lot of particularly convenient and practical properties,

I have to say that third-party controls are now quite popular because he adds vitality and color to the original dead controls.

Written at the end:

To be a programmer or to be a man is not too real and methodical.

To think more, to find a way to "lazy".

Always thinking, standing on the shoulders of giants.

Assigning a value to a form control is written here, of course, there are values assigned to it, assigning the value of the control to the entity, to the data access layer, and then to the operation. It is also used frequently in MIS system. The method is similar to the assignment, and the specific code will be presented to you in the next blog post.

Oノo════════════════════════════╲

│ヽ. Learning and sharing is paramount. │

│ from: http://blog.csdn.net/u010028869 . ヽ│

╲══════════════════════════ ═══ヾ


C # Write a third-party control that implements a key assignment for a form control

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.