Add selected values from a checkbox

1

I'm developing an application for a beauty salon, I'm using the checkbox component on the following screen:

However,whenselectingacheckboxandthendeselecting,theprogramexecutes2timesthecalculation.HowdoIresolvethisissue?

Code:

    
asked by anonymous 26.02.2015 / 20:29

1 answer

1

Instead of using CheckBox , I used CheckedListBox . I created a Service class so I can assign the name and value of each service and also created a method within service to return a populated list with some items.

public class Servico
{
    public string Nome { get; set; }
    public double Valor { get; set; }
    public List<Servico> lista = new List<Servico>();

    public List<Servico> PopularLista()
    {
        lista.Add(new Servico { Nome = "Unha Pé", Valor = 9.50 });
        lista.Add(new Servico { Nome = "Sobrancelha", Valor = 16 });
        lista.Add(new Servico { Nome = "Escovinha", Valor = 198.50 });

        return lista;
    }
}

In method Form1() I already assign values to CheckedListBox :

public Form1()
{
    InitializeComponent();

    var servicos = new Servico();
    servicos.PopularLista();

    ((ListBox)checkedListBox1).DataSource = servicos.lista;
    ((ListBox)checkedListBox1).DisplayMember = "Nome";
    ((ListBox)checkedListBox1).ValueMember = "Valor";
}

And in the Button event, using Linq, I get the values and assignment in the variables:

private void btnRegistrar_Click(object sender, EventArgs e)
{
    List<Servico> servicosSelecionados = checkedListBox1.CheckedItems.OfType<Servico>().ToList();
    string descricaoServicos = servicosSelecionados.Select(x => x.Nome).Aggregate((atual, proximo) => atual + ", " + proximo);
    double valorServicos = servicosSelecionados.Sum(x => x.Valor);
}
    
26.02.2015 / 21:31