C # Passing values between forms

Source: Internet
Author: User

There are several methods for transferring values between C # forms. Each project has its own application. Although it is simple, it is recorded here and shared with you!
1. Use constructors with Parameters
Main form
Private void button_click (Object sender, system. eventargs E)
{
// Pass the control value of the main form as a parameter to the child form
Form2 formchild = new form2 (this. textboxfrm1.text, this. checkboxfrm1.checked );
Formchild. showdialog ();
}

Subform (form2)

// Modify the default no-argument form constructor, accept the passed value, and pass it to the subform control.
Public form2 (string text, bool checkedvalue)
{
Initializecomponent ();
This. textboxfrm2.text = text;
This. checkboxfrm2.checked = checkedvalue;
}

However, this type of value passing is insufficient. After the data in the subform is modified, it cannot be passed to the primary form, that is, the primary form is not affected by the subform. In the actual development process, we often use subforms to modify the data in the main form.
2. There are two types in. Net: Value Type and reference type.
Value types are inherited from valuetype, while valuetype inherits from object. For reference types, valuetype directly inherits from object type. Now let's take a look at how to use the reference type to modify the data in form1 through form2.
Subform code
Private textbox textboxfrm12;
Private checkbox checkboxfrm12;
// The constructor accepts the control reference of the main form. Because it is a reference type, the content points to the same object. Therefore, modifying the value of this object modifies the value of the main form.
Public form2 (textbox heckbo, checkbox heckbox)
{
Initializecomponent ();
// Assign a value
This. textboxfrm2.text = heckbo. text;
This. checkboxfrm2.checked = heckbox. checked;

// Locate the reference
This. textboxfrm12 = heckbo;
This. checkboxfrm12 = heckbox;
}
// Close the subform code
Private void buttonok_click (Object sender, system. eventargs E)
{
// Assign values to textbox and checkbox objects. The same memory is modified here.
This. textboxfrm12.text = This. textboxfrm2.text;
This. checkboxfrm12.checked = This. checkboxfrm2.checked;
This. Close ();
}

The value passing function is also implemented here, but it is not very reasonable. It is annoying to let two Form Controls pass through. If there are more widgets. Of course, we can encapsulate the control that needs to modify the value into the custom struct, but... let's take a look at the following method of passing the value.
III. C # Pass values between forms through arraylist
Main form code

// Arraylist for storing data
Private arraylist listdata;
Public form1 ()
{
Initializecomponent ();
// Initialize arraylist
Listdata = new arraylist ();
Listdata. Add (". Net ");
Listdata. Add ("Java ");
Listdata. Add ("XML ");
Listdata. Add ("WebService ");
// Bind data
Listbox1.datasource = listdata;
}
// Open the subwindow
Private void buttonopen_click (Object sender, eventargs E)
{
// Arraylist is passed as a parameter
Form2 frm2 = new form2 (listdata );
Frm2.showdialog ();
// Modify the arraylist in the subwindow and bind the data again.
Listbox1.datasource = NULL;
// Listbox1.item. Clear (); the error message "the item set cannot be modified after the datasource attribute is set" is displayed.
Listbox1.datasource = listdata;
}

For the error "unable to modify the collection of items after setting datasource properties", refer to http://www.ideaext.com/read.php/312.htm
Subwindow
Arraylist listdata;
Public form2 (arraylist listdata)
{
Initializecomponent (); // Note: You must retain this option when modifying the default constructor. Otherwise, the control in the subwindow cannot be used as an example, the error message "the instance to which the object is not referenced" is displayed. I just made this mistake.
This. listdata = listdata;
Foreach (Object DA in listdata)
{
Listbox1.items. Add (DA );
}
}
// Add a value to arraylist
Private void buttonadd_click (Object sender, eventargs E)
{
If (this. textbox1.text. Trim (). length> 0)
{
This. listdata. Add (this. textbox1.text. Trim ());
This. listbox1.items. Add (this. textbox1.text. Trim ());
}
Else
MessageBox. Show ("Enter the added content! ");
}
// Delete values in arraylist and ListBox
Private void buttondel_click (Object sender, eventargs E)
{
Int Index = This. listbox1.selectedindex;
If (index! =-1)
{
This. listdata. removeat (INDEX );
This. listbox1.items. removeat (INDEX );
}
Else
MessageBox. Show ("Please select to delete items or there are no items to delete! ");
}
// Close the window. The modified value is rebound to The ListBox of the main window.
Private void buttonexit_click (Object sender, eventargs E)
{
This. Close ();
}

Here, we need to remind you that we can compare the two examples by passing the reference type, one is string and the other is arraylist. why can't the data of the main form be modified for the string type? In fact, in. net, modifying the string type is not modifying the original value, but the original value is not changing. Instead, a new string is generated. Below is a good description.
Public class pdtgrp
{
[Stathread]
Static void main (string [] ARGs)
{
String str1 = "ABC ";
String str2 = str1;
Str1 = "123 ";
Console. writeline (str1 );
Console. writeline ("--------------");
Console. writeline (str2 );
Console. writeline ("--------------");
Arraylist al1 = new arraylist ();
Al1.add ("ABC ");
Arraylist Al = al1;
Al2.add ("123 ");
Foreach (Object o in al1)
Console. writeline (string) O );
Console. writeline ("--------------");
Foreach (Object o in Al)
Console. writeline (string) O );
Console. Readline ();
}
}

Run the command to check the output result. In addition, the ref keyword is used for data operations of the value type.
In summary, we use constructors with parameters to implement data interaction between forms, and the code looks clear. In actual development, dataset, datatable, or dataview can be used as parameters, if you only want to modify a row, you can upload a datarow or datarowview.
4. Use custom attributes or methods
The following describes how to use custom attributes or methods to modify data without using the form2_load event.
Click the modify button of the main form to process the function 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;
}
In addition, the listdata1 attribute of the main form is removed,
// Public arraylist listdata1
//{
// Get {return this. listdata1 ;}
//}
Add the listdata2 attribute to the child form,
Public arraylist listdata2
{
Set
{
This. listdata2 = value;
Foreach (Object o in this. listdata2)
This. listboxfrm2.items. Add (O );
}
}
You can also change the attribute to a method,
Public void setlistdata (arraylist listdata)
{
This. listdata2 = listdata;
Foreach (Object o in this. listdata2)
This. listboxfrm2.items. Add (O );
}
The modification button processing function of the main form must also be changed:
Formchild. listdata2 = This. listdata1;
Change
Formchild. setlistdata (this. listdata1 );
In summary, we use the owner attribute of the Form class to establish a bridge between the master and slave forms. Is this similar to the function of passing in the main form as the constructor parameter of the subform; in addition, attributes and methods are used to complete data interaction. I think this implementation method is very practical, especially when data is transmitted without instantiation classes or instances. In the next section, we will explain how to use static classes to complete data interaction.
5. Use static classes
Previously, we used constructors, properties, and methods with parameters to achieve data interaction. Next, we used static classes to complete data interaction between forms. This is also a frequently used data interaction method.
The following is a defined class:
Using system;
Using system. collections;
Namespace ZZ
{
Public class appdatas
{
// Static data member
Private Static arraylist listdata;
// Static Constructor
Static appdatas ()
{
Listdata = new arraylist ();
Listdata. Add ("DOTNET ");
Listdata. Add ("C #");
Listdata. Add ("Asp.net ");
Listdata. Add ("WebService ");
Listdata. Add ("XML ");
}
// Static attributes
Public static arraylist listdata
{
Get {return listdata ;}
}
// Static method
Public static arraylist getlistdata ()
{
Return listdata;
}
}
}
The above contains a static class member, listdata, a static constructor static appdatas (), used to initialize the data of listdata. There is also a static attribute listdata and a static getlistdata () method. They implement the same function, that is, they return listdata

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.