如何以编程方式复制组合框内容
本文关键字:组合 复制 方式 编程 | 更新日期: 2023-09-27 18:04:37
我有这样的代码:
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);
}
}
}
…但它不起作用-我有几个组合框在tabPage上的tabControl上的表单,与cmbxRow0Element0填充项目在设计时。但是,上面尝试将其项目复制到所有其他组合框的操作失败了。
更新这是我现在的代码,它仍然不能工作:
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);
}
}
}
}
也许这与选项卡控件上的选项卡页面上的组合框有关?
更新2
到达下面第一行的断点,但永远不会到达第二行:
if ((C.GetType() == typeof(ComboBox)) & ((C as ComboBox) != this.cmbxRow0Element0))
cmbx = C as ComboBox;
3
更新问题是"find"不够具体-必须指定特定的tabPage。
试试这个:
var items = cmbxRow0Element0.Items.OfType<object>().ToArray();
foreach (ComboBox c in this.Controls.OfType<ComboBox>())
{
c.Items.AddRange(items);
}
如果你使用tabControl
作为容器,那么这意味着你的组合框不是你的表单的直接子元素。所以你需要访问容器的Control
集合,也就是tabControl
。您可以使用this.NameOfYourTabControl.Controls
。
一个快速测试Windows窗体应用程序(VS Express 2012)显示了这是可行的。在一个新的空白Windows窗体应用程序中,拖放三个(或更多)ComboBox控件:
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);
}
}
}
}