✅ How to Update the original instance of my Main Form from another form
I have a Function i'd Like to call from my Mainform and from my second form( the function updates a listbox an my Mainform), to achieve that i created a new instance of my Mainform in my second form, but it apears to only update the listbox on the new Instance of my Main form not on the old one, how can i Update the listbox on the Original Mainform instance.
(i apollogize for my bad english)
This is the Function id Like to call that should update the listbox on my Mainform
This is the Button from my second form that i use to call my function on the first Form.
(i use windows Forms incase thats important)
7 Replies
When you create the second form, pass a reference to the main form into the constructor of the second form
he issue you're facing is because you are creating a new instance of Form1 (MainForm) in your second form (SecondForm) when you call Form1 f1 = new Form1();. This new instance is separate from the original instance of MainForm that was created when your application started, and therefore updating the list box on the new instance doesn't affect the original one.
To update the list box on the original instance of MainForm from SecondForm, you should pass a reference to the original MainForm to SecondForm. One way to do this is to modify the constructor of SecondForm to accept a reference to MainForm and store it in a field. Then, you can call the showMacro method on this reference.
Here's an example modification to your SecondForm: public partial class SecondForm : Form
{
private Form1 mainFormReference; // Field to store reference to MainForm
public SecondForm(Form1 mainForm)
{
InitializeComponent();
mainFormReference = mainForm; // Store the reference
}
private void btnOkayClick(object sender, EventArgs e)
{
try
{
File.WriteAllText(Path.Combine(Form1.macroPath, txbNameInput.Text));
mainFormReference.showMacro(); // Call showMacro on the original MainForm
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("This is not a valid Name! " + ex.Message);
return;
}
}
}
__ And when you create an instance of SecondForm from MainForm, pass this (reference to the current instance of MainForm) to the constructor: SecondForm secondForm = new SecondForm(this);
secondForm.Show(); SecondForm secondForm = new SecondForm(this);
secondForm.Show(); |By doing this, you're working with the original instance of MainForm, and changes made in SecondForm will reflect on it.
The First part seems to work
But when i try to pass ,,this,, it doesnt work
Thx for the help but i think i found a workaround , i can just use the activated Property to call my function everytime my form regains focus. I appreciate your help and effort tho <3
Because you didn't make a constructor to match that
im going to look into it when i have some time, but for now all my problems are solved, still thanks