Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi all,

i've two forms(MainForm & Form2). MainForm contains DataGridview and an Add button, and Form2 has a Save button.I want to Refresh MainForm with Updated data After i clicked Save button of Form2. I used following codes:

this.refresh(),
this.Update(),
refreshform()//function written in mainForm but calling from Form2  


please reply with an exp.
Posted
Updated 20-Jan-11 1:55am
v3

You can make the Form2.Save button public, and have MainForm add an event handler for that button in MainForm, and then all of the updating happens in MainForm automatically.

There's absolutely no need to call into MainForm directly.
 
Share this answer
 
Use delegates and raise an event from Form2. Have your main form subcribe to the event and perform the refresh

C#
public partial class Form1 : Form
{
    Form2 form2;
    public Form1()
    {
        InitializeComponent();
        form2 = new Form2();
        form2.FormDataSaved += new Form2.OnDataUpdated(form2_FormDataSaved);
    }
    void form2_FormDataSaved()
    {
        this.Refresh();
        // However you want to update this form
    }
}

public partial class Form2 : Form
{
    delegate void OnDataUpdated();
    public event OnDataUpdated FormDataSaved;
    public Form2()
    {
        InitializeComponent();
    }
    private void SomeSaveOperation()
    {
        // Whatever your save code is
        this.FormDataSaved();
    }
}
 
Share this answer
 
Comments
JF2015 20-Jan-11 7:59am    
Very detailed example to JSOP'S answer. 5+
Updating one form from another makes me feel a little queasy to be honest. What you're doing is tightly coupling them together and this approach tends to lead to monolithic applications where you're ability to reuse things becomes limited.

You normally have a third thing (some sort of dataset in you case?) which acts as a shared component. Then, one form updates the the dataset and the other responds to it automatically. This way you can then use either form without the other.
 
Share this answer
 
Comments
JF2015 20-Jan-11 8:04am    
Good advice. 5

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