问题
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.
回答1:
Try this:
var items = cmbxRow0Element0.Items.OfType<object>().ToArray();
foreach (ComboBox c in this.Controls.OfType<ComboBox>())
{
c.Items.AddRange(items);
}
If you are using tabControl as a container, then it means your comboboxes aren't direct child element of your Form.So you need to access Control collection of the container which is the tabControl. You can do that using this.NameOfYourTabControl.Controls.
回答2:
A quick test Windows Form app (VS Express 2012) shows this works. In a new blank Windows Form app, drop three (or more) ComboBox controls:
public Form1()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
this.comboBox1.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.comboBox1))
cmbx = C as ComboBox;
if (cmbx != null)
{
foreach (Object item in comboBox1.Items)
{
cmbx.Items.Add(item);
}
}
}
}
来源:https://stackoverflow.com/questions/23818647/how-can-i-copy-combobox-contents-programmatically