Search code examples
c#.netunit-testingmoqtablelayoutpanel

Accessing a combobox's SelectedIndex from within a TableLayoutPanel


I have the following setup:

ComboBox cb1 = new ComboBox();
ComboBox cb2 = new ComboBox();
ComboBox cb3 = new ComboBox();
ComboBox cb4 = new ComboBox();
ComboBox cb5 = new ComboBox();

TableLayoutPanel tlpComboBox = new TableLayoutPanel();
tlpComboBox.ColumnCount = 5;
tlpComboBox.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
tlpComboBox.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
tlpComboBox.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
tlpComboBox.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));
tlpComboBox.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F));

tlpComboBox.Controls.Add(cb1, 4, 0);
tlpComboBox.Controls.Add(cb2, 3, 0);
tlpComboBox.Controls.Add(cb3, 2, 0);
tlpComboBox.Controls.Add(cb4, 1, 0);
tlpComboBox.Controls.Add(cb5, 0, 0);

I'm then trying to check the order of comboBoxes in tlpComboBox. To do this with textboxes, i did the following:

for (i = 0; i < 5; i++)
{
    Assert.AreNotEqual(tlpText.Controls[i].Text.ToString(), i.ToString());
}

Unfortunately SelectedIndex isnt accessible after Controls[i]. when working with the comboboxes and im a little confused as to why.

for (i = 0; i < 5; i++)
{
    Assert.AreNotEqual(tlpComboBox.Controls[i]. "SelectedIndex isnt accessible", i.ToString());
}

Any ideas?

Edit:

https://i.sstatic.net/xBMxh.jpg


Solution

  • You need to cast Controls[i] to ComboBox

    //sample meta code written in notepad
    for (i = 0; i < 5; i++)
    {
        Assert.AreNotEqual(
            ((ComboBox )(tlpComboBox.Controls[i])).SelectedIndex , 
            i.ToString());
    }
    

    This happens because Controls[i] is of type (I guess) Control which doesn't have the SelectedIndex property.