C # form delivery complex data

xiaoxiao2021-03-30  214

When designing form programs, there is often a need to transfer complex data between forms that call each other, and sometimes a child form modifies the content of the parent form. In the blog garden, I saw many people discussing this problem. In the comments of Haitian 1 Gull "Forms, I'm inter-form", I saw that there are such a few practices: 1) Open a static variable 2) Creating a public field in a child form; 3) Use commission and events in the parent form; 4) The child form is used as a parent form.

These measures don't feel very good, it will cause the parent window to be coupled to the child form, and the modification of any form needs to recompile another form. According to the principle of "relying on invert", this tight coupry can be avoided by introducing a result object, and can also pass any complex data. If you need to change the parent form status in the sub-form, you can define the delegate and events in this result object to achieve the purpose. I have given my solution here.

First define a result object to store the results returned by the subform. Also define some events, you can modify the status of the parent form. code show as below:

Using

System;

Namespace

WinParam

{Public delegate void TextChangedHandler (string s); public class cResult {public string Result1 = ""; public string Result2 = ""; public event TextChangedHandler TextChanged; public void ChangeText (string s) {if (! TextChanged = null) TextChanged ( s);}}}

Add a sub-form constructor to allow reception of a result object:

Private

CRESULT R;

public

FRMCHILD (CRESULT R):

THIS

()

{This.r = r;}

Create a child form in a parent form, and subscribe to the CRESULT event:

Private

Void

BtncallChild_Click

Object

Sender, System.EventArgs E)

{CResult r = new cResult (); r.TextChanged = new TextChangedHandler (this.EventResultChanged); frmChild fc = new frmChild (r); fc.ShowDialog (); txtCallResult.Text = "The Result is:" r. Result1 " R.Result2;

Private

Void

EventResultchanged

String

S)

{TXTEVENTRESULT.TEXT = S;}

This ensures that the parent form knows the child, and the child form does not know the parent form. The parent form is not required to recompile the subform. At the same time, both forms rely on the results object, and the stability of the results object also determines the stability of the parent form and the sub-form. Below is the program run results: Note: The supplied code is just a function demonstration, and if actual use needs to add some additional auxiliary code (object release, cancel event subscription, etc.).

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

New Post(0)