C#实现winform用子窗体刷新父窗体及子窗体改变父窗体控件值的方法
本文实例讲述了C#实现winform用子窗体刷新父窗体及子窗体改变父窗体控件值的方法。分享给大家供大家参考。具体如下:
第一种方法:
用委托,Form2和Form3是同一组
Form2
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; namespaceTestMouseMove { publicdelegatevoidSetVisiableHandler(); publicpartialclassForm2:Form { publicForm2() { InitializeComponent(); } privatevoidbutton1_Click(objectsender,EventArgse) { Form3frm=newForm3(newSetVisiableHandler(SetVisiable)); frm.Show(); } privatevoidSetVisiable() { SetVisiable(this.label1,!this.label1.Visible); } privatevoidSetVisiable(Controlcontrol,boolvisiable) { if(this.Controls.Contains(control)) { control.Visible=visiable; } } } }
Form3
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; namespaceTestMouseMove { publicpartialclassForm3:Form { privateSetVisiableHandlerm_setVisible; publicForm3(SetVisiableHandlersetvisible) { InitializeComponent(); this.m_setVisible=setvisible; } privatevoidbtnVisible_Click(objectsender,EventArgse) { if(this.m_setVisible!=null) { this.m_setVisible(); } } } }
第二种方法:
用变量,Form4和Form5是同一组
Form4
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; namespaceTestMouseMove { publicpartialclassForm4:Form { publicForm4() { InitializeComponent(); } #region子窗口刷新父窗口的值 privatestringstrLabel1=""; publicstringStrLabel1 { get { returnstrLabel1; } set { strLabel1=value; this.label1.Text=strLabel1; } } #endregion privatevoidbutton1_Click(objectsender,EventArgse) { Form5form5=newForm5(this);//这里注意传个this form5.Show(); } } }
Form5
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; namespaceTestMouseMove { publicpartialclassForm5:Form { Form4form4=newForm4(); publicForm5(Form4formFrm)//这个构造方法里有参数 { form4=formFrm;//这个必须要有 InitializeComponent(); } privatevoidbutton1_Click(objectsender,EventArgse) { form4.StrLabel1=this.textBox1.Text; } } }
希望本文所述对大家的C#程序设计有所帮助。