Method does not act as expected

Asked

Viewed 54 times

0

When I go to check the following code, there is nothing in any of the ComboBoxes. For me, everything is normal, I see nothing wrong, what can 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);
}
  • I tested your code with two comboboxes and a button to call AttCmb() and worked as expected, the two comboboxes were filled with "Example". Was the end result supposed to be different? What is the code calling? I’m assuming the way the methods are declared was only for SOPT and not so in the code.

  • Now it’s exactly the same.

1 answer

1


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

One solution will be to change the event and the 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);
}

This way, it uses the object that originated the event to fetch the value that was selected (which after the event completes is available in Cmba).

  • As to the CmbA? When the Btn_Click is triggered, nothing happens. In the method Btn_Click there is, in fact, that for, I put it only to represent a person who populated the Arraylist previously.

  • I ran your code and the Cmba is being populated correctly. The problem may be there ArrayList who spoke. Put the breakpoint on it (inside the click event and see if it is correctly filled).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.