Reputation: 2855
I'm working on a form to add new Customers. In this form the users selects an adress in a combobox (cbbAdress). There's also a "new" button next to the adress combobox, which opens up a new form.
frmAdres frmAdres = new frmAdres();
frmAdres.Show();
In this form the users can add a new adress. When they close the form, the combobox (cbbAdress) doesn't update (obviously). I am wondering how I could make the combobox (cbbAdress) on the main form update?
Thanks, Thomas
Upvotes: 0
Views: 2806
Reputation: 23833
Pass to frmAdres
's constructor a reference to the parent form
frmAdres frmAdres = new frmAdres(this);
frmAdres.Show();
in the constructor of the form
private MainForm mainForm;
public frmAfres(MainForm _mainForm) : this()
{
this.mainForm = _mainForm;
}
(using this to call the default constructor). You can then access any control on your main form that has the appropriate accessor. So for your ComboBox
in you MainForm you might have the constructor
public ComboBox myCombo
{
get { retrun this.comboBoxName; }
set { this.comboBoxName = value; }
}
then you could update just this control in your frmAdres
class via
mainForm.myCombo.Update();
Alternatevly, you could just update the entire parent form from frmadres
via
this.ParentForm.Update();
this should update your ComboBox
. I hope this helps.
Upvotes: 2
Reputation: 4088
Make a Singleton :), with a Singleton you can share strings through classes.
public class MySingleton
{
private static Classes.MySingleton _mInstance;
public static Classes.MySingleton Instance
{
get { return _mInstance ?? (_mInstance = new Classes.MySingleton()); }
}
private string _cbbadress;
/// <summary>
/// cbbAdress.
/// </summary>
public string cbbadress
{
get { return _cbbadress; }
set { _cbbadress = value; }
}
}
Edit the string with:
Classes.MySingleton.Instance.cbbadress = cbbAdress.Text;
EDIT: I've learned it this way, of course there are many other ways to do this.
Upvotes: 1
Reputation: 18013
Change you code to something similar below:
using (frmAdres frmAdres = new frmAdres())
{
if (frmAdres.ShowDialog() == DialogResult.OK)
{
//Update your address here
Address d = frmAddress.SelectedAddress;
}
}
obviously you will need to ensure you set the DialogResult to OK on your address form when the Save button is clicked, and add a property to the frmAddress form to read the selected address.
If you click close on the form and Dialog result is not 'OK' then the code in the 'if' block will not get hit.
Placing the form in a 'using' brace will also dispose of it after it leaves the context of the brace which will means you cant forget about disposing of it.
Upvotes: 2