0

First I set the modifier property to "Internal" of comboBox1 on form1.

I used the following code:

form1 f1 = new form1();
object[] obj = new object[f1.comboBox1.Items.Count];
f1.comboBox.Items.CopyTo(obj, 0);
comboBox2.Items.AddRange(obj);`

Is it the best way to do this?

PS: I couldn't make this: Best way to access a control on another form in Windows Forms? to work.

PPS: Making controls is public is not what I like and neither preferred.

Community
  • 1
  • 1
Sujay Kirti
  • 13
  • 1
  • 8
  • 1
    I think you will have a far more maintenable application by using data bindings instead of manual copy of items. If you have two combo boxes that must share items, bind them to the same datasource. If you don't have a DB, you can still use databindings over any kind of object. – Steve B Sep 11 '12 at 12:23
  • I do have a DB (but not implemented yet, working on UI now). Your idea of binding them to a datasource seems good, I'll try it. – Sujay Kirti Sep 11 '12 at 13:32

1 Answers1

2

If you are wanting two drop-down lists with the same items in them it is much better that you store those items somewhere common and build up both combo boxes from there.

e.g.

public class Context{
  ...
  ...
  public List<Foo> FooItems {
    get{...}
  }
}

public class Form1 {
  ...
  combobox.AddRange(this.context.FooItems);
  ...
}

public class Form2 {
  ...
  combobox.AddRange(this.context.FooItems);
  ...
}

This way you prevent coupling between your different forms, and still have only one place where you derive the values that go into the list.

MatthewD
  • 6,719
  • 5
  • 22
  • 41
David Waters
  • 11,979
  • 7
  • 41
  • 76
  • I added a public Class and made a list named list1 there. But it isn't showing up in the forms I want to access from. What may be wrong? Is this correct approach ? – Sujay Kirti Sep 11 '12 at 14:08