How to insert data from timepicker, textbox and all the contents of a datagridview? visual studio 2015

0

I have a big question about ... How do I make multiple entries into my database the records that are inside my datagridview and also outside it?

for example: A trip of such date that would be a data of the datetimepicker, the name that has the trip that would be a textbox and insert all the people that will go to that trip, in this case they would be all those that are in my datagridview .

     Using cn As New SqlConnection(My.Settings.conxion)
        Using cm As New SqlCommand()
            cm.Connection = cn
            cn.Open()
            For Each dr As DataGridViewRow In dgv_retiro.Rows
                cm.CommandText = " INSERT INTO retiros (cod_persona, fec_retiro,nom_evento) VALUES (" & dr.Cells("codigo").Value & "," & Retiros.DateTimePicker1.Value.ToShortDateString & "," & Retiros.txt_evento.Text & ")"
                cm.ExecuteNonQuery()
            Next
            cn.Close()
        End Using
    End Using

What happens is that he throws me the following error

Excepción no controlada del tipo 'System.Data.SqlClient.SqlException' en System.Data.dll

Additional information: The column name 'Testname' is not valid.

Since thank you very much !!!.

    
asked by Sergio Aguiriano 04.10.2017 в 17:27
source

2 answers

1

In the end, solve it like this:

Using cn As New SqlConnection(My.Settings.conxion)
            Using cm As New SqlCommand()
                cm.Connection = cn

                cm.CommandText = "INSERT INTO retiros_asistencia  VALUES(@cod_retiro,@cod_persona)"
                cn.Open()


                For Each dr As DataGridViewRow In dgv_retiro.Rows
                    cm.Parameters.Clear()


                    cm.Parameters.AddWithValue("@cod_retiro", Convert.ToInt32(dr.Cells("cod_retiro").Value))
                    cm.Parameters.AddWithValue("@cod_persona", Convert.ToInt32(dr.Cells("Codigo").Value))
                    cm.ExecuteNonQuery()
                Next
                cn.Close()
            End Using
        End Using

Thank you very much for helping me, really.

    
answered by 04.11.2017 в 03:57
0

Good Sergio,

I think the problem in this is that the single quotes are missing to identify what is a text string and not in the SQL query, in the nom_evento column:

cm.CommandText = " INSERT INTO retiros (cod_persona, fec_retiro,nom_evento) VALUES (" & _ 
  dr.Cells("codigo").Value & "," & Retiros.DateTimePicker1.Value.ToShortDateString & _
  ",'" & Retiros.txt_evento.Text & "')"
    
answered by 05.10.2017 в 08:25