0
votes

I have 3 forms, say Form1 (with datagridview1 and datagridview2), Form2 and Form3. In Form1 I want to open Form2, edit text boxes and when a button is clicked it should pass the values to Form1, which would add it to datagridview1. The same will happen with Form3 after text is entered and passed to Form1 and added to datagridview2. When I click to open Form2, edit the data and pass it through, it adds the values to the datagrid, no problem, but when I click to open Form3 and do the second datagrid, it erases the data in datagridview1. How do I get Form1 to keep the previous datagrid's values and not erase it. At the moment I have this going:

In Form1:

    public string value1
    {
        set { this.dataGridView1.Rows[0].Cells[0].Value = value; }
    }

    public string value2
    {
        set { this.dataGridView2.Rows[0].Cells[0].Value = value; }
    }

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

    private void button2_Click(object sender, EventArgs e)
    {
        Form3 form3 = new Form3();
        form3.Show();
        this.Hide();
    }

Form2:

    public string exampleVal = "example";

    public string value
    {
        get { return exampleVal; }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 frm = new Form1();
        frm.value1 = value;
        this.Hide();
        frm.ShowDialog();
    }

And Form3 has the same properties as above in Form2.

2
Check this stackoverflow.com/questions/20703909/…, in addition, you can store your datasource of gridview into a list and when opening the other pages, you can pass a clone of the list - Ktt

2 Answers

0
votes

From the code you wrote, it seems you are creating a new form 1 every time you click the button and hiding the old one. Instead of creating form one every time. You could create create a delegate method that form 1 can add a method to in form 2 and form 3. Then when the event is called form 2 or form 3 invoke the delegate method.

The other way is to create an event on form 2 and 3 with a derivation from the event args class, that contains the value to be added. Then have form 1 implement the event handler that ties to form 2 and 3.

0
votes

set form2's Constructor like this

public class form2 : Form
{
    Form1 mainForm;
    public form2(Form1 form)
    {
        mainForm = form;
    }
    ....Some other code
 }

and istead of creating new form1 use the mainForm

private void button1_Click(object sender, EventArgs e)
{
    mainForm .value1 = value;
    this.Hide();
    mainForm.Show();
}