Insert records in the form of a table

3

Good afternoon,

I am working on a restaurant system in C # using Windows Forms, which is the part of taking the order:

What I want to achieve in inserting this order in table form in SQL SERVER In the following table:

and how I want it to look when inserting it into SQL is as follows:

The code I am using is the following:

 private void button9_Click(object sender, EventArgs e)
        {
            SqlCommand agregar = new SqlCommand("Insert into Ordenes2 values (@Pedido, @Mesa, @NombreP, @Costo,@Fecha, @Hora)", cadena);

            try
            {
                cadena.Open();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    agregar.Parameters.AddWithValue("@Pedido", variables.orden);
                    agregar.Parameters.AddWithValue("@Mesa", label1.Text);
                    agregar.Parameters.AddWithValue("@NombreP",Convert.ToString(row.Cells[0].Value));

                    agregar.Parameters.AddWithValue("@Costo", Convert.ToSingle(row.Cells[1].Value));
                    label2.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    agregar.Parameters.AddWithValue("@Fecha",label2.Text);
                    agregar.Parameters.AddWithValue("@Hora", label3.Text);

                    agregar.ExecuteNonQuery();
                }

                MessageBox.Show("Orden tomada exitosamente");
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error al agregar " + ex);
            }

            finally
            {
                cadena.Close();
            }
        }

But I have a problem, where should I accommodate the ExecuteNonQuery? since it marks me: The name of the variables has already been declared. It's because of the cycle but I do not know where to put it so that it's not that error.

Greetings, thank you very much.

    
asked by Ezequie Lopez 28.09.2018 в 00:46
source

3 answers

3

You must create a procedimiento almacenado in the following way:

CREATE PROCEDURE SP_GuardarOrden
    @Pedido INT, @Mesa VARCHAR(20), @NombreP VARCHAR(20), @Costo FLOAT, @Fecha DATE, @Hora TIME
AS
BEGIN
    Insert into Ordenes2 values (@Pedido, @Mesa, @NombreP, @Costo,@Fecha, @Hora)
END
GO

and in c #

private void button9_Click(object sender, EventArgs e)
    {
        SqlConnection cadena = new SqlConnection();
        try
        {
            cadena.Open();
            SqlCommand agregar = new SqlCommand("SP_GuardarOrden", cadena);
            agregar.CommandType = CommandType.StoredProcedure;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                agregar.Parameters.AddWithValue("@Pedido", variables.orden);
                agregar.Parameters.AddWithValue("@Mesa", label1.Text);
                agregar.Parameters.AddWithValue("@NombreP", Convert.ToString(row.Cells[0].Value));
                agregar.Parameters.AddWithValue("@Costo", Convert.ToSingle(row.Cells[1].Value));
                label2.Text = DateTime.Now.ToString("yyyy-MM-dd");
                agregar.Parameters.AddWithValue("@Fecha", label2.Text);
                agregar.Parameters.AddWithValue("@Hora", label3.Text);
                agregar.ExecuteNonQuery();
                agregar.Parameters.Clear();
            }
            agregar.Dispose();
            MessageBox.Show("Orden tomada exitosamente");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error al agregar " + ex);
        }

        finally
        {
            cadena.Close();
        }
    }
    
answered by 28.09.2018 в 17:32
2

Thank you very much for taking a little time to read my concern, I managed to insert it in the following way:

Add the line: add.Parameters.Clear (); Which makes the parameters free in each foreach pass.

 private void button9_Click(object sender, EventArgs e)
        {
            SqlCommand agregar = new SqlCommand("Insert into Ordenes2 values (@Pedido, @Mesa, @NombreP, @Costo,@Fecha, @Hora)", cadena);

                try
                {
                    cadena.Open();
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                    agregar.Parameters.Clear();
                        agregar.Parameters.AddWithValue("@Pedido", variables.orden);
                        agregar.Parameters.AddWithValue("@Mesa", label1.Text);
                        agregar.Parameters.AddWithValue("@NombreP", Convert.ToString(row.Cells[0].Value));

                        agregar.Parameters.AddWithValue("@Costo", Convert.ToSingle(row.Cells[1].Value));
                        label2.Text = DateTime.Now.ToString("yyyy-MM-dd");
                        agregar.Parameters.AddWithValue("@Fecha", label2.Text);
                        agregar.Parameters.AddWithValue("@Hora", label3.Text);

                        agregar.ExecuteNonQuery();
                    }

                    MessageBox.Show("Orden tomada exitosamente");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error al agregar " + ex);
                }

                finally
                {
                    cadena.Close();

            }
        }
    
answered by 28.09.2018 в 17:27
2

adding is type SqlCommand , which is perfect. Your code does not really have any faults except for a minor detail.

The SqlCommand , the first round, adds parameters to your Parameters collection (which you do correctly).

But after executing the query, it does not erase its content. Therefore, the collection of parameters still has the ones you added ... and when you hit the loop, you try to add the same parameter that you already entered before, with a new value ... and that's not how it works.

Your solution is simple, clean the parameters column before hitting the round.

To do this, just add a agregar.Parameters.Clear(); after the agregar.ExecuteNonQuery(); .

Likewise, apart from this, I would recommend preparing the query beforehand in this case, because you are always doing the same query and passing the same parameters.

To do this, you just have to change the code a bit:

usign (SqlCommand agregar = new SqlCommand("Insert into Ordenes2 values (@Pedido, @Mesa, @NombreP, @Costo,@Fecha, @Hora)", cadena))
{
    command.Parameters.Add(new SqlParameter("@Pedido", 0));
    command.Parameters.Add(new SqlParameter("@Mesa", 0));
    (etc)....
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        command.Parameters["@Pedido"].Value = variables.orden;
        command.Parameters["@Mesa"].Value = label1.Text;
        (etc)...
        command.ExecuteNonQuery();
   }
}

Notes

Using, prevent you from having to make a command dispose upon completion, do it automatically.
It is not necessary to open the connection in advance, the command opens it automatically. If you have to close it, and make the corresponding dispose.

    
answered by 28.09.2018 в 17:42