Sum selected values from a checkbox

Asked

Viewed 672 times

1

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

inserir a descrição da imagem aqui

However, when selecting a checkbox and then deselecting, the program performs the calculation twice. How to solve this problem?

Code : inserir a descrição da imagem aqui

  • Couldn’t you perform the calculation later? When the person clicks on Register?

  • Ah, I thought, but since there are so many options, ?

  • The Service object, you concatenate the name and value of the services are equal or vary?

  • The values vary, and I concateno mome do servico para que no banco de dados apareca algo tipo ( Nail, Eyebrow, Hydration)

  • http://i.imgur.com/6FnJbdT.png Something like that (the last records)

  • I will make a solution and already put.

  • Quiet, in the waiting

  • Which version of Visual Studio?

  • I’m using visual c#

Show 4 more comments

1 answer

1


Instead of using the CheckBox, I used the CheckedListBox. I created a class Service so I can assign the name and value of each service and also created a method within the service to return me a list populated 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 the method Form1() I already assign the 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 attribute 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);
}

Browser other questions tagged

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