C # compile a third-party control to assign values to the form control with one click,

Source: Internet
Author: User

C # compile a third-party control to assign values to the form control with one click,

,

Cause

 

 

When writing a program, we often write the code above to display the query result to a form. How can we do this? Assign values to one row. This Code is the most boring and error-prone. Have you found that the above Code is doing the same thing-assigning values. If similar code is written more than three times, you must consider whether the process can be encapsulated. Encapsulate a method to automatically complete these repetitive operations.

 

Thinking process

 

 

Similar methods are also written in the project you are using. But it involves many other methods, one set, which is especially inconvenient to pull out. There are also a few unpleasant points: first, the control must be named like the corresponding object property. For example, if the property name of an object is sname, the control name must also be sname. Obviously, this is against the general naming rules we follow. Second, the visibility level of the control must be set to Public. Otherwise, the value cannot be assigned.

Therefore, after studying his method, I wrote it again and made some improvements. It makes up for the two shortcomings above and makes its application more convenient.

The method used is mentioned in the question. When writing third-party controls, you can overwrite the original C # controls and add a new attribute. The attribute added here is named DataField to save the name of the database field. Why? Let's look at it ..

Here I wrote a Demo in C # to illustrate how to write a third-party control and one-key value assignment for the form.

 

Implementation Process

 

 

Create a C # project

Add an interface Interface1:

<Span style = "font-size: 18px;"> interface Interface1 {// define the DataField attribute string DataField {get; set ;}</span>

Add two classes ComboxEx and ComboxEx:

 

Using System. windows. forms; // Add reference internal class TextBoxEx: TextBox, Interface1 {// This class inherits the TextBox Control and interface Interface1 # region Interface1 member public string DataField {get; set ;} # endregion} internal class ComboxEx: ComboBox, Interface1 {# region Interface1 member public string DataField {get; set ;}# endregion}

 

Open the toolbox and we will see:

This is our encapsulated third-party control. Drag it to the form, right-click to view its properties

It has a DataField attribute, so we can assign it a value SID (the Field name of the student table-student ID) and drag several controls and assign values.

Then you can formally write the code and add an entity class StuEntity:

Note: The object attribute name must be consistent with the database field name!

 

Public class StuEntity {// <summary> // student ID // </summary> public string SID {get; set ;} /// <summary> /// name /// </summary> public string sname {get; set ;} /// <summary> /// gender /// </summary> public string sex {get; set ;} /// <summary> /// do not // </summary> public string department {get; set ;} /// <summary> // grade /// </summary> public string grade {get; set ;} /// <summary> /// class /// </summary> public string sclass {get; set ;}}

Note: This is just a small Demo that does not adopt hierarchical writing. All the written methods are put in the FrmHelper class.

 

Public class FrmHelper {// <summary> // obtain the object and assign the row of the DataTable to the entity class enStudent // The encapsulated method in the data center can be used here, convert DataTable into a generic set of object classes, which can save the assignment. /// </Summary> /// <param name = "dr"> DataTable row </param> /// <returns> returns the entity class enStudent </returns> public static StuEntity GetEntity (DataRow dr) {StuEntity enStudent = new StuEntity (); 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 (); enStude Nt. sclass = dr ["sclass"]. toString (); return enStudent;} // <summary> // set the attribute value in the object class, fill in the Form Control /// </summary> /// <param name = "enStudent"> </param> public static void FillFormByEntity (StuEntity enStudent, Form thisfrm) {// Control foreach (Control ctrl in thisfrm. controls) {// whether the interface if (ctrl is Interface1) is inherited {// whether it belongs to the text box if (ctrl is TextBoxEx) {ctrl. text = GetValue (enStudent, (TextBoxEx) ctrl ). dat AField);} // if it belongs to the else if (ctrl is ComboxEx) {(ComboxEx) ctrl) in the drop-down box ). text = GetValue (enStudent, (ComboxEx) ctrl ). dataField);} // if there are other types of controls, you can expand them here. }}}/// <Summary> // use reflection technology, dynamically obtain the value corresponding to the control from the object /// </summary> /// <param name = "enStudent"> entity class </param> // <param name = "DataFiled"> field value </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 the query statement, returns a DateTable /// </summary> /// <returns> DateTable </returns> public static DataTable QueryTable () {using (SqlConnection connection = new SqlConnection ("server = .; database = Re_Charge_sys; user id = sa; password = 123456 ") {SqlCommand cmd = connection. createCommand (); cmd. commandText = @ "select * from Student_info where SID = '000000'"; 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 call:

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 Grade", "Third Grade", "fourth grade"}); 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 ";}


Click the value assignment button. The data read from the database is automatically filled in to the interface control.

 

Third-party controls

 

Of course, this method can also add other attributes, such as NotEmpty, write the method to determine whether it is null in the interface, and then let the control inherit. Set the value of this attribute to True/False to determine whether the control content can be empty. In this way, you do not need to write methods to judge one by one, saving time and effort. Here I have to sigh: standing on the shoulders of giants. In fact, there are already many encapsulated and powerful third-party controls on the Internet. For example, C1Studio is used to encapsulate common controls and add many convenient and practical attributes,

I have to say that the third-party control is very delicious now, because it adds vitality and color to the original dead control.

 

Conclusion:

 

Be a programmer or be a human.

You need to think more and find more ways to be "lazy.

Always thinking, standing on the shoulders of giants.

 

If you assign a value to a form control, you can assign a value to the control, assign the control value to the object, and upload it to the data access layer for further operations. It is also frequently used in MIS systems. The method is similar to the value assignment. The specific code will be presented to you in the next blog.

 

 

O ノ o ═

│ Endless learning and sharing. │

│ From: http://blog.csdn.net/u010028869. sampled │

When there are too many threads, there are too many threads, too many threads

 


 


In C language-> what?

-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */

For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!

In C language-> what?

-> Is a whole. It is used to point to a struct, class in C ++, and other pointers containing sub-data to obtain sub-data. In other words, if we define a struct in C and declare a pointer pointing to this struct, we need to use "->" to retrieve the data in the struct using the pointer ".
For example:
Struct Data
{
Int a, B, c;
};/* Define struct */
Struct Data * p;/* define struct pointer */
Struct Data A = {1, 2, 3};/* declare variable */
Int x;/* declare a variable x */
P = & A;/* point p to */
X = p-> a;/* indicates that the data item a in the struct pointed to by p is assigned to x */
/* Because p points to A, p-> a = A. a, that is, 1 */

For the first problem, p = p-> next; this should appear in the linked list of C language. next here should be a struct pointer of the same type as p, and its definition format should be:
Struct Data
{
Int;
Struct Data * next;
};/* Define struct */
............
Main ()
{
Struct Data * p;/* declare the pointer Variable p */
......
P = p-> next;/* assign the value in next to p */
}
The linked list pointer is a difficulty in C language, but it is also the key. It is very useful to learn it. To be careful, you must first talk about variables and pointers.
What is a variable? The so-called variables should not be simply thought that the amount will become a variable. Let's use the question of our Dean: "Is the classroom changing ?" Change, because there are different people in the classroom every day, but they do not change, because the classroom is always there, and it does not become larger or smaller. This is the variable: There is a constant address and a variable storage space. Under normal circumstances, we only see the variable in the room, that is, its content, but do not pay attention to the variable address, but the C language pointer is the address of the room. We declare that variables are equivalent to building a house to store things. We can directly watch things in the house, while declaring pointers is equivalent to getting a positioner. When a pointer points to a variable, it is to use the pointer to locate the variable. Then we can use the pointer to find the variable "tracked" and get the content in it.
What about struct? The structure is equivalent to a villa composed of several houses, and several houses are bound for use together. Suppose there are many such villas distributed in a big maze, and each villa has a house. The location information of another villa is put in it. Now you have found the first villa with the positioner and obtained what you want from it (the data part of the linked list ), then, calculate the location of the next villa into your positioner (p = p-> next), and go down to the next villa ...... If you go on like this, you will know that the information of a villa on the ground is gone (p-> next = NULL), and your trip is over. This is the process of traversing a linked list. Now you can understand the meaning of p = p-> next!
Write so much. I hope you can understand.
If you want to learn c and C ++ well, you must be familiar with linked lists and pointers!

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.