Insert all CheckedBox into an ingredients database table

1

I'm doing a project for a Pizzeria, the customer can choose the type of dough, quantity and different ingredients, everything works perfectly except the ingredients I do not know how to do it, I tried a CheckedListBox but I did not know how to do it.

After trying the CheckedListBox I tried different CheckedBox because what I want is that all the ingredients of the pizzas appear checked.

Ej Pizza 4 Cheeses (ingredients: Cheddar, Mozzarella, Emmental and Gorgonzola) the client can remove the ingredients he does not want.

Well, I'm going to the point, I want all the CheckedBox that are Checked to be inserted in the database that I have.

I have managed to store only one

Ingredients is a Varchar field and I want you to save all checked items separated by commas

cmd = new SqlCommand("INSERT INTO Pizzas (Ingredientes, Cantidad, Masa, Precio) VALUES(@Ingredientes, @Cantidad, @Masa, @Precio)", con);

            if (cbMozzarella.Checked)
            {
                cmd.Parameters.AddWithValue("@Ingredientes", cbMozzarella.Text);
            }

How can I have it all inserted?

    
asked by El Barto 31.05.2018 в 10:47
source

1 answer

1

A very simple way to generate the string with the ingredients is to use LINQ and String.Join :

cmd = new SqlCommand("INSERT INTO Pizzas (Ingredientes, Cantidad, Masa, Precio) VALUES(@Ingredientes, @Cantidad, @Masa, @Precio)", con);
//la siguiente línea hace lo siguiente:
//- Obtiene todos los controles del formulario que sean de tipo CheckBox
//- Mediante .Where, selecciona todos los que tengan Checked a true
//- Y de esos, selecciona su propiedad Text
var checkboxes = this.Controls.OfType<CheckBox>().Where(x=>x.Checked).Select(x=>x.Text);
string ingredientes= String.Join(",", checkboxes);
cmd.Parameters.AddWithValue("@Ingredientes", ingredientes);

For it to work, the CheckBox must be in Form . If this is not the case and they are for example in a Panel , you must access the collection Controls of said container.

    
answered by 31.05.2018 / 11:00
source