Modify from DataGridView connected to SQL in C #

1

Good morning,

I am developing an application using Windows Forms within C #, it is a record of workers in a store, the users are entered from a form inside the application and they are shown in the following module in a DataGridView which is connected to an SQL server database.

The DataGridView when opening the query module appears as blocked until we press the edit button, that's when the records can be updated, to save the changes the "save" button is pressed but I have two problems:

  • I can only edit the first record, if I try to edit the second one it does not change it.

  • When you edit the first record, change all the records and leave them saved as the first.

  • Annex the code that I am using for the save button:

     private void pictureBox2_Click(object sender, EventArgs e)
            {
                SqlCommand agregar = new SqlCommand("UPDATE Usuarios SET Nombre = @nombre, Apellido = @apellido, Fecha_Nacimiento = @fecha , Telefono = @telefono ", cadena);
    
    
                try
                {
    
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        agregar.Parameters.AddWithValue("@nombre", Convert.ToString(row.Cells["Nombre"].Value));
                        agregar.Parameters.AddWithValue("@apellido", Convert.ToString(row.Cells["Apellido"].Value));
                        agregar.Parameters.AddWithValue("@fecha", Convert.ToDateTime(row.Cells["Fecha Nacimiento"].Value));
                        agregar.Parameters.AddWithValue("@Telefono", Convert.ToString(row.Cells["Telefono"].Value));
                        agregar.ExecuteNonQuery();
                        MessageBox.Show("Usuario Registro Exitoso");
                    }
    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error " + ex);
                }
    
    
            }
    

    If someone could help me with this problem I have, I would be very grateful, greetings and thank you very much.

        
    asked by Ezequie Lopez 23.08.2018 в 16:39
    source

    1 answer

    1

    Your problem is here

    SqlCommand agregar = new SqlCommand("UPDATE Usuarios SET Nombre = @nombre, Apellido = @apellido, Fecha_Nacimiento = @fecha , Telefono = @telefono ", cadena);
    

    when you are doing the update, it is not indicating to which user it is going to update, so you update them all

    I would recommend that you obtain the user code and put it as a condition, I show you how

    SqlCommand agregar = new SqlCommand("UPDATE Usuarios SET Nombre = @nombre, Apellido = @apellido, Fecha_Nacimiento = @fecha , Telefono = @telefono where codusuario = @codigo ", cadena);
    

    so you can modify the record you want.

        
    answered by 23.08.2018 в 16:50