WinForm 两窗体间传值实例

背景:窗体Form1和Form2 Form2由Form1打开(1、模式窗体 2、非模式)
要求:Form2的TextBox值传回Form1的TextBox中

情况一:(模式窗体)Form1 .ShowDialog() 打开Form2

 

Form1:   
 public partial class Form1 : Form   
   {   
       public Form1()   
       {   
           InitializeComponent();   
       }   
  
       private void button1_Click(object sender, EventArgs e)   
       {   
           Form2 frm = new Form2(this,textBox1.Text);//带参数构造Form2(此方法该处带俩参数构造多余)   
         
           if (frm.ShowDialog() == DialogResult.OK)   
           {   
               this.textBox1.Text += frm.ReturnText;//通过Form2的属性获得回传值   
           }   
           frm = null;   
              
       }   
          
   Form2:   
    public partial class Form2 : Form   
   {   
       private Form1 pfrm;   
       private string frm1txt;   
       public Form2(Form1 parentfrm,string frm1text)   
       {   
           InitializeComponent();   
           pfrm = parentfrm;   
           frm1txt = frm1text;   
       }   
              public string ReturnText//回传值的属性   
       {   
           get { return this.frm1txt; }   
       }   
         private void button2_Click(object sender, EventArgs e)//给属性赋值并关闭模式窗体Form2   
       {   
           frm1txt = this.textBox2.Text;   
           this.DialogResult = DialogResult.OK;//*必加 模式窗体打开后 只有DialogResult初始化后才可继续操作 否则值无法传回   
           this.Close();//模式窗体关闭.close()相当于将窗体隐藏 彻底关闭需要用.Dispose()   
       }   
  
       private void button3_Click(object sender, EventArgs e)//关闭   
       {   
           this.DialogResult = DialogResult.Cancel;//同*   
           this.Close();   
       }  

 

你可能感兴趣的:(WinForm)