Error inserting MYSQL by data grid view

-1

The code is as follows, I'm doing an insert from the values of a data grid view

                foreach (DataGridViewRow row in dgvCON.Rows)
                {
                        MySqlCommand cmd = new MySqlCommand();
                        cmd = conectabanco.CreateCommand();
                        if (row.IsNewRow) continue;
                        cmd.Parameters.AddWithValue("@IdProd", row.Cells["Id"].Value);
                        cmd.Parameters.AddWithValue("@QtdProd", row.Cells["Quantidade"].Value);
                        cmd.Parameters.AddWithValue("@NomeProd", row.Cells["Nome"].Value);
                        cmd.Parameters.AddWithValue("@PrecoUnitProd", row.Cells["R$ Unidade"].Value);
                        cmd.Parameters.AddWithValue("@TotalListaConsu", row.Cells["Total"].Value);
                        cmd.CommandText = "INSERT INTO listaconsumo(IdCon, IdProd, QtdProd, PrecoUnitProd, " +
                        "totalListaConsu)VALUES("+idconsumo+", @IdProd, @QtdProd, @NomeProd, @PrecoUnitProd, @totalListaConsu)";

                    cmd.ExecuteNonQuery();
                }

The problem is that when executing Sql, it sends pro insert the value "@IDProd" itself, rather than being replaced by the value of the datagridview

    
asked by anonymous 14.06.2017 / 02:02

1 answer

0

First, the amount of VALUES is different from the number of columns in the INSERT , you are not reporting the column to the NomeProd field. And where do you get row.Cells["R$ Unidade"].Value I believe this is an invalid column name for a datagridview.

Check these questions and give feedback here

The use to access the row cell value is row.Cells[0].Value where 0 is the column index, or row.Cells["key"].Value where key is the name of the object DataGridViewColumn and not the name that appears on the screen. You can directly access the DataGridviewColumn object by entering the Name property. Ex:

row.Cells[nomeDaColuna.Name].Value

Another thing, in the question you said that the @IDProd field was not working, now it passed @NomeProd is not. Which one is right?

Try there.

    
14.06.2017 / 02:30