2015-03-02 148 views
0

我有一個父窗體,其中有一個textbox1和一個panel1和一個button1。我在button1點擊面板1中打開另一個窗體(比如form2)。 form2有一個文本框和按鈕。當我在文本框中輸入一個值並單擊子窗體中的按鈕時,子窗體的textboxvalue應該被複制到父窗體的文本框值,並且panel1應該變爲不可見。父窗體中的子窗體如何訪問父窗體控件的按鈕單擊

我用下面的代碼, 爲Button1點擊(parentform的),

 panel1.Visible = true; 
     Form2 f2 = new Form2(); 
     f2.TopLevel = false; 
     f2.AutoScroll = true; 
     panel1.Location = new Point(this.ClientSize.Width/2 - panel1.Size.Width/2, this.ClientSize.Height/2 - panel1.Size.Height/2); 
     panel1.Anchor = AnchorStyles.None; 
     panel1.Controls.Add(sp); 
     f2.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; 
     f2.Dock = DockStyle.Fill; 
     f2.usrnam = this.usrnam; 
     f2.connectionstring = this.connectionstring; 
     f2.Show(); 

對於子窗體的按鈕點擊,

 string s = textBox1.Text; 
     Form1 f1= new Form1(); /* However this line is wrong , I donot want to initialize the form again i just need a way to access Form1 controls */ 
     f1.panel1.Visible = false; 
     f1.textBox1.Text = s; 
+0

爲什麼在構造函數中沒有通過Form1上的,然後保持一個本地副本它在形式2? – ZoomVirus 2015-03-02 12:53:48

回答

1

兩種形式創建表單對象。喜歡的東西:

在父窗體:

public System.Windows.Forms.Form MyChild 

panel1.Visible = true; 
Form2 f2 = new Form2(); 
f2.MyParent = this; 
this.MyChild = f2; 
------- 
------- 
f2.Show(); 

在孩子:

public System.Windows.Forms.Form MyParent; 

string s = textBox1.Text; 
Form1 f1 = (Form1)this.MyParent; 
f1.panel1.Visible = false; 
f1.textBox1.Text = s; 

而你需要做這些控件的access modifierspublic。在構造函數中

+0

嗨@RagingBull它只是與小修改,我只是添加了一行,Form1 f1 =(Form1)this.MyParent; f1.panel1.Visible = false; f1.MyParent.textBox1.Text = s;非常感謝.....:) :) – Ameena 2015-03-02 13:06:30

0

通Form1上的,然後保持它的本地副本形式2

Form2 f2 = new Form2(this); 
Form1 f1=null; 

public Form2(Form1 f1) 
{ 
    this.f1=f1; 
} 

形式2碼

string s = textBox1.Text; 
f1.panel1.Visible = false; 
f1.textBox1.Text = s; 
相關問題