C # form value passing

Source: Internet
Author: User

Data transmission between forms is a common problem encountered by developers of. Net form applications at the beginning. Here are several common implementation methods. This section applies to operations that extend partially to common classes in a mode form or a non-mode form.

(1) passing constructor Parameters
Passing parameters through the constructor should be a basic parameter transfer method. The reload constructor will instantiate the form through the constructor with parameters.
Define parameter variables in the Form class,
Private object myparams;

Implement constructor,
Public optionform (object parameters)
{
Initializecomponent ();
This. myparams = parameters; // sets the parameter reference.
}

Instantiate a form,
Optionform form = new optionform (myparams );

In actual use, you need to pay attention to whether the input is a reference type or a value type. The processing method varies.

(2) Use Form attributes
Speaking of attribute association, we have mentioned form above. the owner attribute. The following is a complete description based on the msdn document. Most of the text is from the msdn document. to ensure its integrity, some attribute descriptions are extended.

Form. Owner attribute. Obtain or set a form that owns the form.
Syntax: public form owner {Get; set ;}
To make a form owned by another form, you can assign a reference to the form that will become the owner for its owner attribute. When a form falls into another form, it is minimized and closed with the owner form. For example, if form2 is owned by the form form1, when form1 is disabled or minimized, form2 is also disabled or minimized. And the affiliated form is never displayed behind the owner form. The affiliated forms can be used to find and replace windows and other windows. When the owner form is selected, these windows should not disappear.
Form. ownedforms attributes. Returns an array of form objects. These objects indicate all forms owned by the form.
Syntax: public form [] ownedforms {Get ;}
This property returns an array containing all forms owned by this form. To make a form belong to another form, you can use the addownedform method. The form assigned to the owner form remains in the owned State until the removeownedform method is called. If the form is a multi-Document Interface (MDI) parent form, this attribute returns all displayed forms except all the currently opened MDI child forms.
Form. mdichildren attributes. Obtain the array of the Form. These forms indicate that the form is used as the parent multi-Document Interface (MDI) child form.
Syntax: public form [] mdichil.pdf {Get ;}
This attribute allows you to obtain references to all the MDI child forms currently opened in an MDI parent form. To create an MDI child form, the mdiparent attribute assigned to the child form as the form of the MDI parent form. You can use this attribute to perform some operations through all the MDI child forms in sequence. For example, when the MDI parent form is closed, the data is saved to the database, or update fields in the child form based on the operations performed in the application.
Form. mdiparent attribute. Obtain or set the current multi-Document Interface (MDI) parent form for this form.
Syntax: public form mdiparent {Get; set ;}
To create an MDI child form, the mdiparent attribute assigned to the child form as the form of the MDI parent form. You can use this attribute to obtain the global information required by all child forms or call the method for performing operations on all child forms.
Form. activeform static attributes. Obtains the current active form of the application.
Syntax, public static form activeform {Get ;}
Indicates the current active form, or if there is no active form, it is null reference. You can use this method to obtain a reference to the current active form to perform operations on the form or its controls.
Form. activemdichild attribute. Obtain the multi-Document Interface (MDI) subwindow of the current activity.
Syntax: public form activemdichild {Get ;}
Returns the form of the currently active MDI child window, or returns a blank reference if no child window exists. You can use this method to determine whether there are any opened MDI child forms in the MDI application. You can also use this method to perform operations on the Child Window of the MDI child window from the parent window of the MDI child window or from other forms displayed in the application.
Containercontrol. parentform attribute. Obtain the form to which the container control is assigned.
Syntax: public form parentform {Get ;}
The form that the container control is assigned.

(3) Use public attributes (Note: I usually use this method)
Public attributes are also a common method. The default access modifier of the control added by the Form Designer is private and can be set to public or internal (visible within the Assembly) to make public. For example, to publish a button in a form, you can access the related properties of the button, and you can also register an event or cancel event registration. For example,
Optionform form = new optionform ();
Form. buttonok. Click + = new eventhandler (buttonok_click );
Form. showdialog ();

Controls on controls or variables that only allow reading or modifying access can be controlled by attributes. Modify the (1) method to remove the overloaded constructor and add attributes to achieve the same effect.
Public object myparams
{
Get {return this. myparams ;}
Set {This. myparams = value ;}
}

(4) use public methods
The public method is similar to the attribute, and the preceding implementation is as follows,
// Obtain parameters
Public object getparams ()
{
Return this. myparams;
}
// Set parameters
Public void setparams (Object myparams)
{
This. myparams = myparams;
}

(5) using static classes this method can be simply understood as global sharing of static variables. The following code can be used to clearly understand the static classes,
Public static class parametersettings
{
// Public static variables
Public static string username = "zhengzuo ";
// Private static variable
Private Static string userrole = "Administrators ";
// Private static variable
Private Static string Password = "http://blog.csdn.net/zhzuo ";
// Internal Attributes
Internal static string userrole
{
Get {return userrole ;}
}
// Public attributes
Public static string Password
{
Get {return password ;}
Private set {Password = value ;}
}
}

You can perform the following operations in the areas to be accessed,
String username = parametersettings. Username;
String Password = parametersettings. Password;
String userrole = parametersettings. userrole;
Parametersettings. Username = "Zheng Zuo"; // modify it to a new user name.

(6) form implementation Singleton Mode
The Singleton mode is one of the most common modes in our development process. Some people often talk about implementing Singleton for the main form in the technical community, but I personally think this is not a proper practice because it is not necessary. Another custom class is used for demonstration. Assume that the userlogininfo class is used to save the user creden。 after logging on to the system.
/* ===================================================== ==========
Program Zheng Zuo 2006-4-23 http://blog.csdn.net/zhzuo
========================================================== ======= */
Public class userlogininfo
{
// Implement the singleton mode for thread security.
Private readonly static userlogininfo currentuserinfo = new userlogininfo ();
// Provides global access points
Public static userlogininfo currentuserinfo
{
Get {return currentuserinfo ;}
}
// Block explicit instantiation, but cannot block reflection calls.
Private userlogininfo ()
{
}
// Public variables
Public String username;
// Private variable
Private Static string userrole;
// Private variable
Private Static string password;
// Internal Attributes
Internal string userrole
{
Get {return userrole ;}
Set {userrole = value ;}
}
// Public attributes
Public String Password
{
Get {return password ;}
Internal set {Password = value ;}
}
}

Access in other code,
Userlogininfo. currentuserinfo. Username = "Zheng Zuo ";
Userlogininfo. currentuserinfo. userrole = "dotnetlover ";
Userlogininfo. currentuserinfo. Password = "http://blog.csdn.net/zhzuo ";

There are many implementation methods for the singleton mode. When writing, you need to consider whether you need to ensure the thread security of instance access to avoid unexpected situations. To improve performance, you can consider inert instantiation. For more information about the singleton mode, refer to another article.

(7) Publish events for subscription
Passing parameters through events is supposed to be a method of pushing implementation. When an event is generated, it passively acquires relevant data. A custom event is used to demonstrate data transmission.
When customizing events, the standard method first defines an event parameter class, either using the base class eventargs directly or inheriting from eventargs to implement its own parameter class, assume that the custom base class is named optionsettingeventargs,
// Option to set the event parameter class
Public class optionsettingeventargs: eventargs
{
Private string changedpath;
// Constructor
Public optionsettingeventargs (string changedpath)
{
This. changedpath = changedpath;
}
// Read Parameters
Public String changedpath
{
Get {return this. changedpath ;}
}
}

The preceding parameter classes only contain one modified path parameter. Next, we will add event definitions to the original optionform. Here we will use the generic class provided in. NET 2.0 for implementation.
// Define the event
Public event eventhandler <optionsettingeventargs>
Optionsettingchanged;
The Program for writing events is as follows,
// Triggers the optionsettingchanged event
Protected virtual void onoptionsettingchanged (optionsettingeventargs E)
{
If (optionsettingchanged! = NULL)
{
Optionsettingchanged (this, e );
}
}

Modify the event handler of the select button in the file directory to activate the event. The direct data input method from the text box is not considered.
// Set a new path in the directory dialog box
Private void buttonbrowser_click (Object sender, eventargs E)
{
Folderbrowserdialog dialog = new folderbrowserdialog ();
Dialogresult result = dialog. showdialog (this );
If (result = dialogresult. OK)
{
If (this. textboxpath. Text! = Dialog. selectedpath)
{
This. textboxpath. Text = dialog. selectedpath;
Optionsettingeventargs ARGs = new optionsettingeventargs (dialog. selectedpath );
Onoptionsettingchanged (ARGs );
}
}
}
Now, all preparations are complete. The call code is as follows,
Optionform form = new optionform ();
// Register an event
Form. optionsettingchanged + = new eventhandler
(Form_optionsettingchanged );
Form. showdialog ();
Verify the correctness of the following Event Handlers,
Private void form_optionsettingchanged (Object sender, optionsettingeventargs E)
{
String newpath = E. changedpath;
MessageBox. Show (this, String. Format ("the new path is" {0 }". ", Newpath)," prompt ");
}

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.