Reputation: 1832
I know how to pass an object from parent-form to sub-form using constructors.
For example in the parent form, I do this:
WithdrawDialog dlg = new WithdrawDialog(cust.Accounts);
Child form:
public WithdrawDialog(BankAccountCollection accounts)
{
InitializeComponent();
PopulateComboBox(accounts);
}
// populate comboBox with accounts
private void PopulateComboBox(BankAccountCollection accounts)
{
foreach (BankAccount b in accounts)
{
comboBoxAccount.Items.Add(b);
}
}
I'm still trying to get the hang of Properties... How would I use properties instead of overloaded constructors to do this?
Upvotes: 0
Views: 2326
Reputation: 3738
While it is possible to do this with a public property, it wouldn't be recommended. A method is more suited for this because you need to perform logic to populate the control.
If you're just trying to get it out of your constructor, make PopulateComboBox public or internal (if the parent and child are in the same assembly), and think about changing the name to something more descriptive, like "PopulateBankAccounts" or "AddBankAccounts".
Then you can do something like this in the parent form:
using (WithdrawDialog dlg = new WithdrawDialog())
{
dlg.AddBankAccounts(cust.Accounts)
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.Ok)
{
//etc...
}
}
Upvotes: 0
Reputation: 11403
In the parent form:
WithdrawDialog dlg = new WithdrawDialog();
dlg.Accounts = cust.Accounts;
Child form:
public class WithdrawDialog
{
private BankAccountCollection _accounts;
public WithdrawDialog()
{
InitializeComponent();
}
public BankAccountCollection Accounts
{
get { return _accounts; }
set { _accounts = value; PopulateComboBox(_accounts); }
}
// populate comboBox with accounts
private void PopulateComboBox(BankAccountCollection accounts)
{
foreach (BankAccount b in accounts)
{
comboBoxAccount.Items.Add(b);
}
}
}
Upvotes: 0
Reputation: 4669
in WithdrawDialog do:
public WithdrawDialog()
{
InitializeComponent();
}
public BankAccountCollection Accounts{
set{
PopulateComboBox(value);
}
}
in the calling form do:
WithdrawDialog dlg = new WithdrawDialog{Accounts=cust.Accounts};
(this curly braces invoke the Object Initializer)
Upvotes: 0
Reputation: 44931
Here you go:
WithdrawDialog dlg = new WithdrawDialog();
dlg.accounts = cust.Accounts;
dlg.Show();
public WithdrawDialog()
{
InitializeComponent();
}
private BankAccountCollection m_Accounts;
public BankAccountCollection accounts {
get {
return m_Accounts;
}
set {
m_Accounts = value;
PopulateComboBox(m_Accounts);
}
}
// populate comboBox with accounts
private void PopulateComboBox(BankAccountCollection accounts)
{
foreach (BankAccount b in accounts)
{
comboBoxAccount.Items.Add(b);
}
}
Alternatively, PopupComboBox could be rewritten to use the accounts property:
// populate comboBox with accounts
private void PopulateComboBox()
{
foreach (BankAccount b in this.accounts)
{
comboBoxAccount.Items.Add(b);
}
}
Upvotes: 3