为什么从一个组合框的项目不能复制到另一个? [英] Why do Items from one comboBox not copy to another?

查看:188
本文介绍了为什么从一个组合框的项目不能复制到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表格的tab控件的标签页上有多个组合框。尝试循环使用控件无效(请参阅 this )。

I have multiple comboboxes on a tabpage on a tabcontrol on a form. Trying to loop through the controls has not worked (see this).

所以,我试图从另一个角度来看:根据他们的名字找到控件。作为初始POC,我只是想通过提供在设计时为空的组合框的名称(cmbxRow0Element1)来强制它,并将项目从cmbxRow0Element0分配给它。但这两个尝试:

So, I tried to go at it from another angle: finding the controls based on their name. As an initial POC, I just wanted to brute force it by providing the name of one of the combo boxes that is empty at design time ("cmbxRow0Element1") and assign the items from cmbxRow0Element0 to it. But both this attempt:

Control ctrl = this.Controls["cmbxRow0Element1"];
ComboBox cmbx = ctrl as ComboBox;
var items = cmbxRow0Element0.Items.OfType<object>().ToArray();
cmbx.Items.Add(items);

...这个:

Control ctrl = this.Controls["cmbxRow0Element1"];
ComboBox cmbx = ctrl as ComboBox;
foreach (Object item in cmbxRow0Element0.Items)
{
    cmbx.Items.Add(item);
}

...结果在 System.NullReferenceException is unhandled
_HResult = -2147467261
_message =对象引用未设置为对象的实例。

cmbx.Items.Add()

...on the call to cmbx.Items.Add()

为什么是

我想让它最终成为:

string cmbxName;
int cmbxCount = getCountOfComboBoxes();
for (int i = 0; i < cmbxCount; i++)
{
    cmbxName = string.Format("cmbxRow0Element{0}", i);
    Control ctrl = this.Controls[cmbxName];
    ComboBox cmbx = ctrl as ComboBox;
    cmbx.Items.Add("Twain");
    cmbx.Items.Add("Steinbeck");
    cmbx.Items.Add("Saroyan");
    cmbx.Items.Add("Frost");
    cmbx.Items.Add("Hardy");
    cmbx.Items.Add("Stegner");
}


推荐答案

> cmbxRow0Element1 不是您的表单的直接子元素。使用 NameOfYourTabControl.Controls [cmbxRow0Element1] ,或更一般地:

Because cmbxRow0Element1 is not direct child element of your Form. Use NameOfYourTabControl.Controls["cmbxRow0Element1"], or more generally:

this.Controls.SelectMany(x => x.Controls).First(x => x.Name == "cmbxRow0Element1");

这篇关于为什么从一个组合框的项目不能复制到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆