I've got this code:
private void FormMain_Shown(object sender, EventArgs e)
{
ComboBox cmbx;
foreach (Control C in this.Controls)
{
if (C.GetType() == typeof(ComboBox))
{
cmbx = C as ComboBox;
//cmbx.Items.AddRange(cmbxRow0Element0.Items); <= illegal
object[] obj = new object[cmbxRow0Element0.Items.Count];
cmbxRow0Element0.Items.CopyTo(obj, 0);
cmbx.Items.AddRange(obj);
}
}
}
...but it doesn't work - I have several combo boxes on a tabPage on a tabControl on a Form, with cmbxRow0Element0 populated with items at design time. The above attempt to copy its items to all the other comboboxes fails, though.
UPDATE
This is the code I now have, and it still doesn't work:
public FormMain()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
this.cmbxRow0Element0.Items.Add(String.Format("Item {0}", i.ToString()));
}
foreach (Control C in this.Controls)
{
ComboBox cmbx = null;
// The & test ensures we're not just finding the source combobox
if ((C.GetType() == typeof(ComboBox)) & ((C as ComboBox) != this.cmbxRow0Element0))
cmbx = C as ComboBox;
if (cmbx != null)
{
foreach (Object item in cmbxRow0Element0.Items)
{
cmbx.Items.Add(item);
}
}
}
}
Perhaps it's something to do with the comboboxes being on tab pages on the tab control?
UPDATE 2
A breakpoint on the first line below is reached, but the second line is never reached:
if ((C.GetType() == typeof(ComboBox)) & ((C as ComboBox) != this.cmbxRow0Element0))
cmbx = C as ComboBox;
UPDATE 3
The problem was the "find" was not being specific enough - the particular tabPage has to be specified. For more details, see this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…