2010-11-11 128 views
0

我有一個主「父窗口」包含一個按鈕和一個文本框。 我有另一個窗口「孩子」窗口,當我在文本框中輸入一些文本並單擊主窗口上的按鈕時會觸發。現在子窗口包含另一個文本框和一個按鈕。我需要做的是在子窗口的文本框中輸入一些文本,然後當我點擊子窗口上的按鈕時,父窗口上的文本框應該更新我從子窗口輸入的文本。 這裏是樣本:從c中的子窗口訪問父窗口中的控件#

Form1.cs的

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 

namespace childform 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Form2 tempDialog = new Form2(this); 
      tempDialog.ShowDialog(); 
     } 

     public void getText(string text) 
     { 
      textbox1.Text = text; 
     } 

    } 
} 

Form2.cs

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 

namespace childform 
{ 
    public partial class Form2 : Form 
    { 
     private Form1 m_parent; 

     public Form2(Form1 frm1) 
     { 
      InitializeComponent(); 
      m_parent = frm1; 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      m_parent.getText(textbox1.text); 
     } 
    } 
} 

任何想法如何做到這一點?

+0

form2.field.text? – 2010-11-11 23:06:08

+0

[如何從C#中的子窗口訪問和更改父窗口控件的值]的可能重複(http://stackoverflow.com/questions/4160396/how-to-access-and-change-value-of-parent-窗口控制從孩子窗式-CS) – 2014-01-31 07:56:53

回答

0

1)在窗體2(孩子的): 添加屬性來獲取其在文本框寫的文字:

Public string TheText 
{ 
    get { return textbox1.Text; } 
} 

而且DialogResult屬性設置按鈕Ok知道用戶按確定當他關閉表單時,不是關閉按鈕。

2)在Form1(父)中: 檢查用戶是否按下確定按鈕,添加從Form2屬性theText中取值。

private void button1_Click(object sender, EventArgs e) 
{ 
    Form2 tempDialog = new Form2(); 
    if (tempDialog.ShowDialog() == DialogResult.Ok) 
     textbox1.Text = tempDialog.TheText; 
} 

祝你好運!