2015-04-23 28 views
-2

我怎樣才能直接從一個窗體的值傳遞給另一個?接收者表單將在屏幕上顯示,並將從主表單發送監聽傳遞值。如何使這種方法的相反

我知道一個方法來做到這一點與代表和事件,但我不是我想要的。

我需要用相反的方式。以下是我可以做這些代碼行。這樣做只能將Form2傳遞給Form1(主窗體)。我需要這種方法的相反。因此,Form1將成爲發送者Form2將成爲接收者,並在屏幕上顯示時實時傳輸。

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

    private void button1_Click(object sender, EventArgs e) 
    { 
     Form2 f = new Form2(); 
     f.IdentityUpdated += new Form2.IdentityUpdateHandler(Form2_ButtonClicked); 
     f.Show(); 
    } 

    private void Form2_ButtonClicked(object sender, IdentityUpdateEventArgs e) 
    { 
     textBox1.Text = e.FirstName; 
    } 
} 

public partial class Form2 : Form 
{ 
    public delegate void IdentityUpdateHandler(object sender, IdentityUpdateEventArgs e); 
    public event IdentityUpdateHandler IdentityUpdated; 

    public Form2() 
    { 
     InitializeComponent(); 
    } 

    private void Form2_Load(object sender, EventArgs e) 
    { 
     string sFirstName = txtFirstName.Text; 
     IdentityUpdateEventArgs args = new IdentityUpdateEventArgs(sFirstName); 
     IdentityUpdated(this, args); 
    } 
} 

public class IdentityUpdateEventArgs : System.EventArgs 
{ 
    private string mFirstName; 
    public IdentityUpdateEventArgs(string sFirstName) 
    { 
     this.mFirstName = sFirstName; 
    } 

    public string FirstName 
    { 
     get { return mFirstName; } 
    } 
} 
+0

事件是這樣做的正確方法。你有什麼問題? – Blorgbeard

+0

@Blorgbeard,我覺得這足夠我在這裏解釋。 –

+0

那麼它*不足以讓我理解你。但是,其他人可能會這樣做。 – Blorgbeard

回答

0

嘗試這種方式

public partial class Form1 : Form 
{ 
    public delegate void IdentityUpdateHandler(object sender, EventArgs e); 
    public event IdentityUpdateHandler IdentityUpdated; 

    public Form1() 
    { 
     InitializeComponent(); 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     Form2 form2 = new Form2(); 
     form2.Show(); 
     IdentityUpdated(this, new EventArgs()); 
    } 
} 

public partial class Form2 : Form 
{ 
    public Form2() 
    { 
     InitializeComponent(); 
     Form1 form1 = (Form1)Application.OpenForms["Form1"]; 
     form1.IdentityUpdated += Form1OnIdentityUpdated; 
    } 

    private void Form1OnIdentityUpdated(object sender, EventArgs eventArgs) 
    { 
     MessageBox.Show("received"); 
    } 
} 
+0

「這個」對於你所建議的內容不是很有用的解釋......也可以考慮解釋你正在回答的問題的版本。 –

+0

@ uowzd01讚賞。非常出色。拯救我的一天。 –

+0

@ uowzd01,我還添加了一個檢查Form1是否已經出現在屏幕上的方法,如果Form2已經顯示了它自己,那麼只是實時傳遞值。這正是我正在尋找的東西。 –