Method does not act as expected

0

When I check the following code, there is nothing in any of the ComboBoxes . For me, everything is normal, I do not see anything wrong, what can it be?

public FormExemplo()
{
    ExemploList = new List<string[]>;
    CmbB.Enabled = false;
}
private void AttCmbA(ComboBox A) 
{
    A.Items.Clear();
    for (i = 0; i < ExemploList.Count; i++)
    {
        A.Items.Add(ExemploList[i][0]);
    }
} 
private void AttCmbB(ComboBox A, ComboBox B) 
{
    B.Items.Clear();
    for (int i = 0; i < ExemploList.Count; i++)
    {
        if (A.SelectedItem.Equals(ExemploList[i][0]))
        {
            for (int j = 0; j < 3; j++)
            {
                CmbB.Add(ExemploList[i][j]);
            }
        }
    }
} 
private void CmbA_SelectedIndexChanged(object sender, EventArgs e)
{
    CmbB.Enabled = true;
    AttCmbB(CmbA, CmbB);
}
private List<string[]> ExemploList;
private void Btn_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        ExemploList.Add(new string[3] { (2 * i).ToString(), (2 * (i++)).ToString(), (2 * (i * i).ToString() });
    }
    AttCmbA(CmbA);
}
    
asked by anonymous 24.05.2014 / 03:36

1 answer

1

The problem I encountered in your code was in the AttCmbB(...) method. Accessing the SelectedItem property as it has, returns null because at this point the selection has not yet been made (we are within the SelectedIndexChanged event).

One solution is to change the event and method to this form:

private void AttCmbB(ComboBox B, object selectedItem)
{
    B.Items.Clear();
    for (int i = 0; i < ExemploList.Count; i++)
    {
        if (selectedItem.Equals(ExemploList[i][0]))
        {
            for (int j = 0; j < 2; j++)
            {
                CmbB.Items.Add(ExemploList[i][j]);
            }
        }
    }
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox comboBox = (ComboBox)sender;
    AttCmbB(CmbB, comboBox.SelectedItem);
}

In this way, it uses the object that originated the event to fetch the value that was selected (which after the completion event is available in CmbA).

    
24.05.2014 / 17:51