Refreshing object in a separate form

I have an application that displays data from a MySQL table. Basically my application consists of two forms: a main form and a form for adding stuff to the database.

The main form displays all records in the database and related information. When the user wants to add a new record to the database, a secondary form opens that asks for information. Once the information is filled in, the user clicks the "Submit" button and the form is closed. My problem is that when the second form is closed listBox

, the main form is not updated to reflect the newly added record.

Here's the code that gets executed when the user submits an additional form:

    private void closeWindow()
    {
        mainForm parent = new mainForm();
        parent.listParts.Refresh();
        this.Close();
    }

      

Is there any reason when I call listBox

to update it doesn't show my recently added information? Am I calling in the wrong order? Or Refresh()

does the method not even work?

Any help would be appreciated! Alternatively, if you know the best way to do this, I love hearing it!

+3


source to share


3 answers


The problem is you are updating the wrong form:

private void closeWindow()
{
    mainForm parent = new mainForm();
    parent.listParts.Refresh();
    this.Close();
}

      



Since you are using:, new mainForm()

you allocate a completely separate instance of "mainForm" and update its contents. This will not affect the existing open form.

I would recommend passing a reference to mainForm

the secondary form constructor. Then it will know which instance of mainForm it should use to call Refresh()

.

+4


source


Reed got an answer with why you didn't work, here is one possible solution to fix it:

in event handler for MainForm:



var otherForm = new SomeOtherForm();
otherForm.Closed += (sender, args) =>
{
  //update the listbox in MainForm here
};

      

If you need information from the second form to update the list, create a public property in SomeOtherForm

that provides the data needed for MainForm

.

+2


source


I think you need to reload data again. fetch sets the data source again

Place the parent property on your child form, which is the type of your first form.

something like that.

Your parent form

public partial class KitTypes : Form
{

 public void ReloadData()
 {
   // Get the data and Set as datasource of control
 }

}

      

And the shape of a child

public partial class Kit : Form
{
    private int _KitId=0;
    private KitTypes _parentForm = null;


 public Kit(KitTypes parentForm)
 {
   _parentForm =parentForm;
 }
}

      

And from your first form, when you create an object of this, pass the parent form as a parameter

  Kit objChild=new kit(this);
  objChild.Show();

      

Now in your child you can call the public method of the parent form like this

this._parentForm.ReloadData(); 

      

+1


source







All Articles