Easily master data interaction between Windows forms in .NET

xiaoxiao2021-03-06  67

Easily mastered the data interaction between the Windows Forms in .NET. This framework provides a conditional, object-oriented, scalable class set that enables you to develop a wealth of Windows applications. A Windows Form represents an instance of the System.Windows.Forms.form class in the .NET architecture. The author is in the 9CBS technology forum. NET sections often see someone asking how to deliver data between two FORMs, access the value inside the other party form. For those who have experienced programmers, it is not a deep thing. For beginners, these foundations are often a problem, and this phenomenon is often more complicated. They will learn. What is actually not really understanding it, the foundation is not solid, so I want to write some articles in this regard through my own experience of the form of the form, to give the school .NET friend reference, also borrowed This opportunity communicates with friends, please ask your friends to pay for usa, and I have divided into three parts. One. Using parametric constructor we have to do prepared to create two forms, below is the layout of two forms, very simple: Description: Form1 is the main form, including control: text box TextBoxFRM1, multi-selection box checkboxfrm1 and buttons ButtonEdit; FORM2 for a child form, contains control: text box textboxfrm2, multi-selection box checkboxfrm2 and buttons Buttonok, Buttoncancel. When we create a new form, the designer generates a default constructor: public form2 ();} It does not take parameters, since we have to pass some of FORM1 to FORM2, why not Do you have an article in the constructor of Form2? Suppose we want to implement the text box in Form2 to display the value of the TextBoxFRM1 in Form1, modify the constructor of the child form: public form2 {initializeComponent (); this.TextBoxFrm2.text = text;} Add Form1 in Form1 button click event handler follows: private void buttonEdit_Click (object sender, System.EventArgs e) {Form2 formChild = new Form2 (this.textBoxFrm1.Text); formChild.Show ();} as a parameter we this.textBoxFrm1.Text Transfer to the sub-form constructor, open in a non-mode mode, the open formchild's text box shows the "main form" text, is it very simple, then let's pass a Boolean data to the child form.

Public Form2 (String Text, Bool CheckedValue) {INITIALIZECMOMPONENT (); this.textBoxfrm2.text = text; this.checkboxfrm2.checked = checktedValue;} In the main form, the modification button click to process, I use the way to open the mode window. in fact in this case it was not clear what, respectively, private void buttonEdit_Click (object sender, System.EventArgs e) {Form2 formChild = new Form2 (this.textBoxFrm1.Text, this.checkBoxFrm1.Checked); formChild.ShowDialog () The result is expected, but it is clear that there is no shortcomings, and the main form cannot be transmitted to the main form after the data modification in the childfield, that is, the effect of the main form is not subject. In the actual development process, we often use the child form to modify the data in the main form, how to solve it? There are two types, value types, and reference types in .NET. The value type is inherited from valueetype, and ValueType is inherited from Object; for reference type it directly inherits the Object type. Let us look at how to modify the data in Form1 through Form2. Or let us modify the code of Form2. Private TextBox textBoxFrm12; private CheckBox checkBoxFrm12; public Form2 (TextBox heckbo, CheckBox heckbox) {InitializeComponent (); this.textBoxFrm2.Text = heckbo.Text; this.checkBoxFrm2.Checked = heckbox.Checked; this.textBoxFrm12 = heckbo; this. Checkboxfrm12 = heckbox;} Now we have passed the data of two reference types: TextBox type, and checkbox; additional two class data member TextBoxFRM12 in Form2, checkboxfrm12 is used to save the variables from the constructor, but they Controls containers that do not belong to Form2. OK button click event edit function Form2: private void buttonOK_Click (object sender, System.EventArgs e) {this.textBoxFrm12.Text = this.textBoxFrm2.Text; this.checkBoxFrm12.Checked = this.checkBoxFrm2.Checked; this.Close ( );} the above code we completed by the Text and checkBoxFrm2.Checked textBoxFrm2 assigned textBoxFrm12 checkBoxFrm12 and modifications to the main form and textBoxFrm1 checkBoxFrm2 because textBoxFrm1 textBoxFrm12 are the same and referenced checkBoxFrm2 and also checkBoxFrm12. The function is achieved here, but I always feel that it is not very reasonable, let the two form controls come back, now I will give an appropriate example. Modified two forms: Description: In this example, our two forms have added a listbox to display the content in ArrayList.

Controls in the main form: ListBoxFRM1, Buttonedit; Subform Control: Listboxfrm2, TextBoxAdd, Buttonadd, ButtonEdit, Buttonok. This time we use ArrayList as transfer data, define class data members in Form1: Private arraylist listdata1; add memory allocation to ListData1 in the constructor, and generate data is finally bound to listboxfrm1, public form1 () {InitializationComponent This.listdata1 = new arraylist (); this.listdata1.add ("dotnet"); this.listdata1.add ("c #"); this.listdata1.add ("asp.net"); this.listdata1. Add ("WebService"); this.listdata1.add ("xml"); this.listboxfrm1.datasource = this.listdata1;} In addition, the modification of the modification button click the event handler as follows: private void button -dit_click (Object Sender, System . Eventargs e) {form2 formchild = new form2 (this.listdata1); formchild.showdialog (); this.listboxfrm1.datasource = null; this.listboxfrm1.datasource = this.listdata1;} relative to the main form, pair of sub-windows The body is modified accordingly, and the class data member is also added in Form2: Private ArrayList ListData2; is used to save the reference to ListData1 in the main form. Modify the constructor: public Form2 (ArrayList listData) {InitializeComponent (); this.listData2 = listData; foreach (object o in this.listData2) {this.listBoxFrm2.Items.Add (o);}} Here, let listData2 same point listData1 The same reference; there is no binding of ListBoxFRM and filled. Ok, the following is the time to operate.

Add processing function code as follows: private void buttonadd_click (object sender, system.eventargs e) {if (this.TextBoxAdd.Text.trim (). Length> 0) {this.listdata2.add (this.textBoxAdd.Text.trim) )); This.listboxfrm2.tems.add (this.TextBoxAdd.Text.trim ());} else messagebox.show ("Please enter the added content!");} Delete processing code as follows: Private void buttonDel_click (Object Sender , System.EventArgs e) {int index = this.listBoxFrm2.SelectedIndex;! if (index = - 1) {this.listData2.RemoveAt (index); this.listBoxFrm2.Items.RemoveAt (index);} else MessageBox.Show ("Please select the delete item or no delete item!"); The data is modified in the body, and the main form will display the updated data. Here is something to remind, compare two examples, we all pass the reference type, one is string, the other is ArrayList, why cannot modify the main form of the STRING? In fact, the modification of the String type in .NET is not modified by the original value. The original value has not changed, but regenerates a new string, which is a good description.

Public class zzconsole {[stathread] static void main (string "args) {string str1 =" abc "; string str2 = str1; string str2 = str1; str1 =" 123 "; console.writeline (str1); console.writeline (" --- ----------- "); console.writeline (str2); console.writeline (" ------------ "); arraylist al1 = new arraylist () Al1.add ("abc"); arraylist al2 = AL1; Al2.Add ("123"); Foreach (Object O in AL1) Console.writeline ("----- ---------- "); Foreach (Object O in Al2) Console.writeline () O); console.readline ();}} When you want to see the output results, Data operations for value types To use the REF keyword. Summary, we have implemented the data interaction between the forms through the constructor of the parameters, and the code looks more clear. In the actual development process, you can use DataSet, DataTable, or DataView as a parameter. Of course, if just want to modify a line. You can pass a DATAROW or DATAROWVIEW. In the following article, let's take a look at how to use two other ways to implement data interaction. two. Add an attribute or method 1 to the form. Get or set the form that has this form using the Owner property using the Form class. To make a form return to another form, assign a reference to its OWNER attribute to become a form of a form that will become the owner. When a form is hosted by another form, it minimizes and closes the owner form. For example, if the Form2 is returned to the form FORM1, it is turned off or minimized when the FORM1 is turned off or minimized. And the accessory form is never displayed behind the owner form. The accessory form can be used to find and replace the window, and these windows should not disappear when the owner form is selected. To determine the form owned by a parent form, use the OwNedForms property. The above is the SDK help document, let's use it below. First, use the second example in the first article, the form is as follows: Description: In this example, our two forms add a listbox to display the contents of ArrayList. Controls in the main form: ListBoxFRM1, Buttonedit; Subform Control: Listboxfrm2, TextBoxAdd, Buttonadd, ButtonEdit, Buttonok.

The main form is or defined by a class data member, and the private arraylist listdata1; instantiates it in the constructor, fill the data, and finally bound to ListBoxFRM1. The constructor is as follows: public form1 () {INITIALIZECMPONENT (); this.listdata1 = new arraylist (); this.listdata1.add ("dotnet"); this.listdata1.add ("c #"); this.listdata1.add "ASP.NET"); this.listdata1.add ("Webservice"); this.listdata1.add ("xml"); this.listboxfrm1.datasource = this.listdata1;} Master's modification button processing function: private void buttonEdit_Click (object sender, System.EventArgs e) {Form2 formChild = new Form2 (); formChild.Owner = this; formChild.ShowDialog (); this.listBoxFrm1.DataSource = null; this.listBoxFrm1.DataSource = this.listData1; } We set formchild.owner as this, so that the sub-form and the main form are connected, of course, we can also change to the following: private void button -dit_click (Object sender, system.eventargs e) {form2 formchild = New Form2 (); This); this); this.listboxfrm1.datasource = null; this.listboxfrm1.datasource = this.listdata1;} But not yet, the current ListData1 variable outside the main form is not available, private arraylist listdata1; Must be modified to PUBLIC access modifier, public arraylist listdata1; can also be realized by property Now, public arraylist listdata1 {get {return this.listdata1;}} I use attributes and feel more flexible and clear. Below is a modification of FORM2, and the constructor is restored.

Public form2 () {initializationComponent (); additionally adds a form's LOAD event, in its event handler, get data in the main form, Private Void Form2_Load (Object Sender, System.EventArgs E) {Form1 Pareform = (Form1) this.owner; this.listdata2 = peach (Object O in this.listdata2) this.listboxfrm2.items.add (o);} Some people will ask, why not put the above code Place it in the constructor? The following is not better, public form2 () {INITIALIZECMOMPONENT (); Form1 Pareform = (Form1) this.owner; this.listdata2 = peach (Object O in this.listData2) this.listboxfrm2.Items.Add (O ); Then I will be wrong to you, because after the main form modification button is clicked, start executing form2 formchild = new form2 (); and executing Form1 Pareform in the constructor during the instantiation of Form2. (Form1) this.owner; at this time, this.owner is no value, is an empty reference, then the following code is definitely problem, this.listdata2 = peach (Object O in this.listdata2) this .listboxfrm2.items.add (o); FormChild.owner = this; this code is used after the entire FORM2 instantiation; this code is used, so use the Form2_Load event. How can I not use the FORM2_LOAD event? Wait until let's modify the code to implement it.

The following subform code has no change, private void buttonadd_click (object sender, system.eventargs e) {if (this.TextBoxAdd.Text.trim (). Length> 0) {this.listdata2.add (this.textboxAdd.Text .Trim ()); this.listboxfrm2.tems.add (this.TextBoxAdd.Text.trim ());} else messagebox.show ("Please enter the added content!");} Private void buttonDel_click (Object Sender, System . Eventargs e) {int index = this.listboxfrm2.selectedIndIndex; if (index! = - 1) {this.listdata2.removeat (index); this.listboxfrm2.items.removeat (index);} else messagebox.show (" Please select Delete! "); value. 2. Using Custom Attributes or Method Let's talk about how to use custom properties or methods to complete data modification features without using the form2_load event.

Click the Edit button handler main form as follows: private void buttonEdit_Click (object sender, System.EventArgs e) {Form2 formChild = new Form2 (); formChild.ListData2 = this.listData1; formChild.ShowDialog (); this.listBoxFrm1. DataSource = null; this.listboxfrm1.datasource = this.listdata1;} and we remove the list of the main form of listData1 properties, // public arraylist listdata1 // {// get {return this.listdata1;} //} Add ListData2 attribute, public arraylist listdata2 {set {this.listdata2 = value; foreach (object o in this.listdata2) this.listboxfrm2.Items.Add (O);}} can also change the properties to methods, Public void setListData (arraylist listdata) {this.listdata2 = listdata; foreach (objectbo in this.listdata2) this.listboxfrm2.Items.add (o);} and modify the button processing function in the main form : Formchild.listdata2 = this.listdata1; change to formchild.setListData (this.listdata1); summary The function of the form of the form is similar to the implementation of the function; in addition, the properties and methods are used to complete the data interaction, I think this implementation is very practical, especially if it doesn't need to instance or have an example. In the case of delivery of data. Next article Let us use a static class to complete the interaction of data.

three. The following is a static class using the class definition: using System; using System.Collections; namespace ZZ {public class AppDatas {private static ArrayList listData; static AppDatas () {listData = new ArrayList (); listData.Add ( "DotNet") ListData.Add ("C #"); ListData.Add ("ASP.NET"); ListData.Add ("WebService"); ListData.Add ("XML");} public static arraylist listdata {get {return listdata; }}} Public static arraylist getListData () {return listdata;}}} The above contains a static class member, ListData, a static constructor static appdata () to initialize the data of ListData. There is also a static property ListData and a static getListData () method, and they achieve the same feature is to return ListData.

Since there are many articles, there is a lot of articles, here is not fine, the following is the complete code: form1.cs file Using system; use system.drawing; useing system.collections; using system.componentmodel; using system.windows.Forms ; namespace ZZ {public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.Button buttonEdit; private System.Windows.Forms.ListBox listBoxFrm1; private System.ComponentModel.Container components = null; public Form1 () {InitializeComponent (); this.listBoxFrm1.DataSource = AppDatas.ListData;} protected override void Dispose (bool disposing) {if (disposing) if (components = null!) components.Dispose (); base.Dispose (disposing);} [Stathread] static void main () {Application.run (new form1 ());} private void initializecomponent () { this.buttonEdit = new System.Windows.Forms.Button (); this.listBoxFrm1 = new System.Windows.Forms.ListBox (); this.SuspendLayout (); this.buttonEdit.Location = new System.Drawing.Point (128 , 108); this.buttonedit.name = "buttonedit"; this.buttonedit.Tabindex = 1; this.buttonedit.text = "Modification"; this.buttonedit.click = new system.eventhandler (this.buttonedit_click); this.buttonedit_click; .listboxfrm1.itemheight = 12; this.listboxfrm1.location = new system.drawing.point (12, 8); this.listboxfrm1.name = "listboxfrm1";

this.listBoxFrm1.Size = new System.Drawing.Size (108, 124); this.listBoxFrm1.TabIndex = 2; this.AutoScaleBaseSize = new System.Drawing.Size (6, 14); this.ClientSize = new System.Drawing .Size (208, 141); this.controls.add (this.ListBoxfrm1); this.controls.add (this.buttonedit); this.name = "form1"; this.text = "form1"; this.ResumeLayout false);} private void buttonEdit_Click (object sender, System.EventArgs e) {Form2 formChild = new Form2 (); formChild.ShowDialog (); this.listBoxFrm1.DataSource = null; this.listBoxFrm1.DataSource = AppDatas.ListData;} }} Form2.cs file using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace ZZ {public class Form2: System.Windows.Forms.Form {private System.Windows.Forms. Butto n buttonOK; private System.ComponentModel.Container components = null; private System.Windows.Forms.ListBox listBoxFrm2; private System.Windows.Forms.Button buttonAdd; private System.Windows.Forms.Button buttonDel; private System.Windows.Forms. TextBox textBoxAdd; public Form2 () {InitializeComponent (); foreach (object o in AppDatas.ListData) this.listBoxFrm2.Items.Add (o);} protected override void Dispose (bool disposing) {if (disposing) if (components! =

null) components.Dispose (); base.Dispose (disposing);} private void InitializeComponent () {this.buttonOK = new System.Windows.Forms.Button (); this.listBoxFrm2 = new System.Windows.Forms.ListBox ( ); this.buttonAdd = new System.Windows.Forms.Button (); this.buttonDel = new System.Windows.Forms.Button (); this.textBoxAdd = new System.Windows.Forms.TextBox (); this.SuspendLayout (); This.buttonok.location = new system.drawing.point (188, 108); this.Buttonok.name = "buttonok"; this.buttonok.tabindex = 0; this.buttonok.text = "OK"; this .buttonOK.Click = new System.EventHandler (this.buttonOK_Click); this.listBoxFrm2.ItemHeight = 12; this.listBoxFrm2.Location = new System.Drawing.Point (8, 8); this.listBoxFrm2.Name = "listBoxFrm2 " this.listboxfrm2.size = new system.drawing.size (168, 124); this.listboxfrm2.tabindex = 2; this.buttonadd.location = new system.drawing.point (188, 44); this.buttonadd.name = "buttonAdd"; this.buttonAdd.TabIndex = 3; this.buttonAdd.Text = "increase"; this.buttonAdd.Click = new System.EventHandler (this.buttonAdd_Click); this.buttonDel.Location = new System.Drawing. Point (188, 76); this.buttondel.name = "buttondel"; this.buttondel.tabindex = 4;

this.buttonDel.Text = "Delete"; this.buttonDel.Click = new System.EventHandler (this.buttonDel_Click); this.textBoxAdd.Location = new System.Drawing.Point (188, 12); this.textBoxAdd.Name = "textBoxAdd"; this.textBoxAdd.Size = new System.Drawing.Size (76, 21); this.textBoxAdd.TabIndex = 5; this.textBoxAdd.Text = ""; this.AutoScaleBaseSize = new System.Drawing.Size (6, 14); this.clientsize = new system.drawing.size (272, 141); this.Controls.add (this.textBoxAdd); this.controls.add (this.buttond); this.controls.add ( This.buttonadd; this.Listboxfrm2; this.controls.add (this.buttonok); this.name = "form2"; this.text = "form2"; this.ResumeLayout (false); } Private void buttonok_click (Object sender, system.eventargs e) {this .Close ();} private void buttonadd_click (object sender, system.eventargs e) {if (this.textBoxAdd.Text.trim (). Length> 0) {appdata.com.listdata.add (THIS.TEXTBOXADD.TEXT.TRIM ))); This.ListBoxfrm2.tems.add (this.textBoxAdd.Text.trim ());} else messagebox.show ("Please enter the added content!");} Private void buttonDel_click (Object Sender, System.EventArgs e ) {INDEX = this.listboxfrm2.selectedIndIndex; if (INDEX! =

转载请注明原文地址:https://www.9cbs.com/read-85984.html

New Post(0)