c# – CheckBox com CheckBox Externa

Question:

I have a Form with a DropDownlist with CheckBox inside, and I have an external CheckBox that selects and deselects all.

My doubt is the following.

When I uncheck one of the items in DropDown the CheckBox "Select All" should be unchecked and when I selected all items it should be checked. But when I do the events are interacting with each other and are giving errors.

Does anyone know a way to do this?

This is the CheckBox Select All code.

private void cbSelAll_CheckedChanged(object sender, EventArgs e)
{
    if (cbSelAll.Checked == true)
    {
         //Ao selecionar a flag Selecionar todos marca todos os itens
         for (int i = 0; i < cb.CheckBoxItems.Count; i++)
         {
              cb.CheckBoxItems[i].Checked = true;
         }
    }
    else
    {
        //Ao desmarcar a flag Selecionar todos desmarca todos os itens
        for (int i = 0; i < cb.CheckBoxItems.Count; i++)
        {
            cb.CheckBoxItems[i].Checked = false;
        }
    }
}

Answer:

Make a flag to know when the event is being fired by another, and not be processed:

    bool processando = false;
    private void cbSelAll_CheckedChanged(object sender, EventArgs e)
    {
        if (!processando)
        {
            processando = true;

            if (cbSelAll.Checked == true)
            {
                //Ao selecionar a flag Selecionar todos marca todos os itens
                for (int i = 0; i < cb.CheckBoxItems.Count; i++)
                {
                    cb.CheckBoxItems[i].Checked = true;
                }
            }
            else
            {
                //Ao desmarcar a flag Selecionar todos desmarca todos os itens
                for (int i = 0; i < cb.CheckBoxItems.Count; i++)
                {
                    cb.CheckBoxItems[i].Checked = false;
                }
            }


            processando = false;
        }

    }

Coloque o if:

if (!processando)
{
  processando = true;
//Processo
  processando = false;
}

within the other events as well.

Scroll to Top