Click here to Skip to main content
15,905,414 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,
I have two forms: Form1 contains a DataGridView and a Button - this Button uses to show Form2, there is abc() function in the Form1 . Form2 contains a Button to add a string to DataGridView of Form1. I code as follows (use delegate):
- Form1:
C#
public void abc(string x)
        {
            dataGridView1.Rows.Add(x);
        }
 private void button1_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.Show();
        }


(abc() function is used to add string x to dataGridView1 of Form1)

- Form2:
C#
public delegate void func(string x);
.........
private void button1_Click(object sender, EventArgs e)
        {
            func f = null;
            Form1 frm = new Form1();
            f = frm.abc;
            f("def");
        }


When I run, click to Button of Form1 then Form2 shows, after that I click to Button of Form2, but I don't see anything in dataGridView1 of Form1! How to do this? Thanks.
Posted

1 solution

This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

—SA
 
Share this answer
 
v2
Comments
Andrewpeter 18-Aug-12 0:40am    
Thanks SA, I have read it but I have not understood more about "delegate", this is a small example that I practise "delegate", so please help me understand it clearly.
Sergey Alexandrovich Kryukov 18-Aug-12 0:52am    
That was not my answer, about the delegate-based method, but by Ciumac Sergiu. You can load the same page and send him a comment to ask for further explanation, but probably you can use the link he provided.

I fixed my link above a bit to point to the same page, but to my answer, specifically. You are very welcome to ask уour questions about my approach (or about delegates or anything else :-)

--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900