0

I want to access the combobox selected items of form1 in form2. Getting values of combobox from form1 to form2 in c#.

Dilip wk
  • 23
  • 1
  • 1
  • 4
  • modify it with static and public – Madhawa Priyashantha Sep 10 '14 at 02:49
  • Almost certainly the wrong approach. `Form2` most likely shouldn't even know that `Form1` exists. What is the EXACT relationship between the forms? – jmcilhinney Sep 10 '14 at 02:55
  • @jmcilhinney I would agree with you if this was wpf. So tell me, why shouldn't Form2 know about Form1? Are we following a design pattern here? If the two forms need to interact with each other, there is no harm in keeping them coupled, imo. – Simon Farshid Sep 10 '14 at 03:02
  • 1
    @SepehrFarshid, we are trying to write good code, I would hope. Whether it's Windows Forms or WPF or something else should be irrelevant. It is generally good practice for created objects not to have to know about their creator. For one thing, if `Form2` is dependent on `Form1` then you can't use `Form2` again anywhere else. – jmcilhinney Sep 10 '14 at 03:04
  • @jmcilhinney I would use an interface in this situation myself. But hey I thought that was too complicated to explain here. If you want to show us a more correct way, go on. Post your answer and I'll remove mine :) – Simon Farshid Sep 10 '14 at 03:08

1 Answers1

1

The quick way is to make sure that the controls on Form2 are public, then populate them like this...

Form2 f2 = new Form2();
f2.ControlName.Value = this.ControlName.Value;
f2.Show();

However, this is bad code as everyone has pointed out. I would encapsulate this into a public method that passes one or more values on to Form2.

in Form1...

Form2 f2 = new Form2();
f2.Populate(txtValue1.Text, dtDateTime.Value);
f2.Show();

in Form2...

public void Populate(string Value1, DateTime Value2)
{
   txtValue1.Text = Value1;
   dtValue2.Value = Value2;
}

This way you can instantiate Form2 whenever you want, and populate it as needed. It is thread safe, it is neat and clean, it doesn't make anything public or static that shouldn't be.

Ty H.
  • 905
  • 8
  • 8
  • While a method is not wrong, I'd do it slightly differently. If this data is required then I'd have it passed in via the constructor, so that an instance cannot be created without providing the required data. If it's not required then I'd tend to use a property for each value, especially if the data needed to be pulled out again afterwards. – jmcilhinney Sep 10 '14 at 04:15
  • 1
    I understand that is a common approach, my hesitation has always been that I don't know when/if .Net will try to call the default constructor for the Form. So I generally don't mess with it. Plus I may not know what I want the form to say until later, or I may want to update it periodically. Calling a method makes all that possible, I just have to be disciplined enough to remember to call Populate when the time is right. – Ty H. Sep 10 '14 at 04:21