The previous article introduced the method of delegating events to realize the subform calling the control of the parent form. This article will use parameter passing to achieve the sharing of an entity object.
The code used in this article is also modified based on the previous article.
1. The parent form
uses the shared entity object innoBERT as the parameter of the subform constructor. The code is as follows in the "Modify this line" section.
if (subFormPPGTx[i] == null || subFormPPGTx[i].IsDisposed) { subFormPPGTx[i] = new SubFormPPG(innoBERT, i);//修改此行 subFormPPGTx[i].Text = formTitle; subFormPPGTx[i].Name = formName; //subFormPPGTx[i].Tag = i; subFormPPGTx[i].SendToParent += new SubFormPPG.SendFun(RecvInfo); subFormPPGTx[i].Show(this); } else { subFormPPGTx[i].WindowState = FormWindowState.Normal; subFormPPGTx[i].Activate(); }
2. Subform
First define a class field, then modify the constructor of the subform and add parameters to receive the entity object passed by the parent form. In this way, the entity object innoBERT can be called in the subform.
InnolightBERT innolightBERT;bool formStatus = false;private int ID; public delegate void SendFun(int number); public event SendFun SendToParent; public SubFormPPG(InnolightBERT innoBERT, int ID) { InitializeComponent(); this.innolightBERT = innoBERT;//接收对象 this.ID = ID; }
3. Use the
subform to call the properties of the shared entity object.
private void SubFormPPG_Load(object sender, EventArgs e) { this.GetPPGSetting(this.ID); }private void GetPPGSetting(int channel) { try { switch (channel) { case 0: this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx1_Swing; break; case 1: this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx2_Swing; break; case 2: this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx3_Swing; break; case 3: this.comboBoxSwing.SelectedIndex = (int)innolightBERT.Tx4_Swing; break; default: return; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
The above is the content of Self-Study C#06 from 0--Multiple Form Shared Objects. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!