I have multiple comboboxes on a tabpage on a tabcontrol on a form. Trying to loop through the controls has not worked (see this).
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);
...and this one:
Control ctrl = this.Controls["cmbxRow0Element1"];
ComboBox cmbx = ctrl as ComboBox;
foreach (Object item in cmbxRow0Element0.Items)
{
cmbx.Items.Add(item);
}
...result in "System.NullReferenceException was unhandled _HResult=-2147467261 _message=Object reference not set to an instance of an object."
...on the call to cmbx.Items.Add()
Why???
I want it to eventually be something like:
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");
}