Results 1 to 34 of 34

Thread: [RESOLVED] save datagridview multiple rows

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Resolved [RESOLVED] save datagridview multiple rows

    Hi, i want to save into my sql server 2000 database multiples rows of a datagridview. i tryed something that first was working good, but i did a code change removing a column so now i'm trying to save again but i can't do it. It's shows me a message error like this: THERE ARE FEWER COLUMNS IN THE INSERT STATEMENT THAN VALUES ESPECIFIED IN THE VALUES CLAUSE. I rewrite the code, delete and add a new table and my code has the same values in the insert than my values clause. I don't know what else i have to do.

    Here is my code, thanks for your answers.

    Code:
    Private Sub cmdAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAceptar.Click
            Try
    
                Const CCon As String = "data source = DATASERVER;Initial Catalog= CATV;user id = sa;password=sa"
                Dim sqlCon As New Data.SqlClient.SqlConnection(CCon)
    
                Dim sqlQry As New SqlClient.SqlCommand("Insert into COMPRAS_ENC(PED_NRO, PED_FCH, PROV_ID, TIP_COMPRA) values ('" & _
                txtNumShop.Text & "', '" & dtpFecha.Text & "', '" & cboCodProv.Text & "',  '" & cboCompra.Text & "' )", sqlCon)
                sqlCon.Open()
    
                If grid1.Rows.Count > 0 Then
                    For i As Integer = 0 To grid1.Rows.Count - 1
                        Dim sqlQry2 As New SqlClient.SqlCommand("Insert into DETALLE_COMPRA(PED_NRO, PED_LIN, MED_ID, CANT_COM, PRE_UNI) values ('" & _
                        txtNumShop.Text & "', " & Me.grid1.Rows(i).Cells(0).Value.ToString & ", '" & _
                        Me.grid1.Rows(i).Cells(1).Value.ToString & "', " & _
                        Me.grid1.Rows(i).Cells(2).Value.ToString & ", " & _
                        Me.grid1.Rows(i).Cells(3).Value.ToString & ")", sqlCon)
                        sqlQry2.ExecuteNonQuery()
                    Next
                End If
                sqlQry.ExecuteNonQuery()
                sqlCon.Close()
    
            Catch ex As Exception
                MessageBox.Show(ex.Message)
    
            End Try
            'Me.Close()
    
        End Sub

  2. #2
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Re: save datagridview multiple rows

    THERE ARE FEWER COLUMNS IN THE INSERT STATEMENT THAN VALUES ESPECIFIED IN THE VALUES CLAUSE.
    Means that you are passing values less than the required.. For example your insert statement requires 3 values and you are supplying only 2 values. Check the InsertQuery....
    Please mark you thread resolved using the Thread Tools as shown

  3. #3
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    Is your datagridview unbound?

    Concatenating an SQL statement is a poor way from the security point of view and I would check whether your values in the textboxes and the datagridview contain commas, semicolons, quotes or double quotes.

    Use parametrized queries instead. (Search this forum for parametrized queries if you don't know how).

  4. #4
    A SQL Server fool GaryMazzone's Avatar
    Join Date
    Aug 2005
    Location
    Dover,NH
    Posts
    7,493

    Re: save datagridview multiple rows

    I count 5 files in the columns to insert into list and only 4 values in the value list.
    Sometimes the Programmer
    Sometimes the DBA

    Mazz1

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i did it, i used a breakpoint to see what values are passing to each field. But nothing, i could see that values of the datagrid are no passing, but i don't know how to resolve it 'cause this code worked good first.

  6. #6

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i have five values in the insert statement and five in the values clause.
    PED_NRO
    PED_LIN
    MED_ID
    CANT_COM
    PRE_UNI

    Values especified:
    '" & txtNumShop.Text & "',
    " & Me.grid1.Rows(i).Cells(0).Value.ToString & ",
    '" & me.grid1.Rows(i).Cells(1).Value.ToString & "',
    " & Me.grid1.Rows(i).Cells(2).Value.ToString & ",
    " & Me.grid1.Rows(i).Cells(3).Value.ToString & ")", sqlCon)

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    what do you mean with bound or unbound, i don't know well english so this word is not familiar to me

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i think that the problem is in the datagridview values, but i don't know how to resolve it

  10. #10
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    When you specify a DataSource for your datagridview it becomes bound to that datasource or if you fill the values manually it's unbound. With data bound controls you have to change the datasource rather than the controls themselves while with unbound control you change the contents of such controls directly.
    Also, since you're concatenating your sql query I asked you to check whether values contain characters "," ";", quote (') or double quote (").
    And I still suggest that you parametrize your query (use named parameters)

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    well i write the values directly in the datagrid and enable add, update and delete rows.

    Now i'm trying with parametrized values, the purchase header works fine but i'm trying wth the purchase detail table, but i don't know how to indicate to save each row of te datagrid. with my old code i tryed this:
    If grid1.Rows.Count > 0 Then
    For i As Integer = 0 To grid1.Rows.Count - 1
    Dim sqlQry2 As New SqlClient.SqlCommand("Insert into DETALLE_COMPRA(PED_NRO, PED_LIN, MED_ID, CANT_COM, PRE_UNI) values ('" & _
    txtNumShop.Text & "', " & Me.grid1.Rows(i).Cells(0).Value.ToString & ", '" & _
    Me.grid1.Rows(i).Cells(1).Value.ToString & "', " & _
    Me.grid1.Rows(i).Cells(2).Value.ToString & ", " & _
    Me.grid1.Rows(i).Cells(3).Value.ToString & ")", sqlCon)
    how could i do it with parameters?

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    and the value "PRE_UNI" (unit price) contains a (,) 'cause i use decimals numbers

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    when i assign the value taked for the textbox to the parameter i do this
    rsProveedor = Me.cboCodProv.Text
    cmd.Parameters("@proveedor").Value = rsProveedor
    but how could i get each value of each datagrid row?

  14. #14
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    Quote Originally Posted by jess21 View Post
    and the value "PRE_UNI" (unit price) contains a (,) 'cause i use decimals numbers
    THIS IS THE SOURCE OF YOUR PROBLEM!

    There's more, you won't be able to add "2,23" value because db engine understands only "2.23"

    You should specify data types for your datagridview columns.

    To get the value of the row(4) column (5) you should use:

    DataGridView.Rows(4).Items(5)

    If you substitute a variable instead of 4 you can iterate through all the rows.

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    but sometimes i will use 20, 10, 3, 5, 15 rows.

  16. #16
    A SQL Server fool GaryMazzone's Avatar
    Join Date
    Aug 2005
    Location
    Dover,NH
    Posts
    7,493

    Re: save datagridview multiple rows

    I would absoultley say it is IMPERITIVE that you use parameters for doing this. If you don't want to change the , to a . (10,23 to 10.23) then you need to use parameters
    Sometimes the Programmer
    Sometimes the DBA

    Mazz1

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i have this code to define the unit price of each medicine 'cause in the purchase order the unit price is based on boxes no unit prices for example, if i buy a medicine like amoxicillin the supplier write in the purchase order 20 boxes of amoxicillin x 100 caps = $15 each one. So in my win form i have to write 2000 caps of amoxicillin and $30(total price) so the program will calculate the unit price. This is my code to calculate the unit price (i tryed to use a (.) instead a (,) but i couldn't
    Dim calculo As Double
    Dim cantidad As Double = CDbl((Me.grid1.Rows(e.RowIndex).Cells(2).Value))
    Dim precio As Double = CDbl((Me.grid1.Rows(e.RowIndex).Cells(4).Value))
    Dim columna As Integer = 4

    'subtotal de cada fila
    calculo = Val(precio) / Val(cantidad)

    Me.grid1.Rows(e.RowIndex).Cells(3).Value = calculo

  18. #18
    A SQL Server fool GaryMazzone's Avatar
    Join Date
    Aug 2005
    Location
    Dover,NH
    Posts
    7,493

    Re: save datagridview multiple rows

    I couldn't mean the left front tire fell off right?
    Sometimes the Programmer
    Sometimes the DBA

    Mazz1

  19. #19
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    Try it

    This code can give you errors if the datatype in the database table does not match with datagridview columns data types.
    If there are errors, tell me what are the datatypes of fields in the data table.

    vb.net Code:
    1. Private Sub cmdAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAceptar.Click
    2.         Try
    3.  
    4.             Const CCon As String = "data source = DATASERVER;Initial Catalog= CATV;user id = sa;password=sa"
    5.             Dim sqlCon As New Data.SqlClient.SqlConnection(CCon)
    6.  
    7.             Dim Sql As String = "INSERT INTO COMPRAS_ENC(PED_NRO, PED_FCH, PROV_ID, TIP_COMPRA) Values " & _
    8.                                     "(@ped_nro, @ped_fch, @prov_id, @tip_compra)"
    9.  
    10.             Dim sqlQry As New SqlClient.SqlCommand(Sql, sqlCon)
    11.  
    12.             With sqlQry.Parameters
    13.                 .AddWithValue("@ped_nro", txtNumShop.Text)
    14.                 .AddWithValue("@ped_fch", dtpFecha.Text)
    15.                 .AddWithValue("@prov_id", cboCodProv.Text)
    16.                 .AddWithValue("@tip_compra", cboCompra.Text)
    17.             End With
    18.  
    19.             sqlCon.Open()
    20.             Dim sql2 As String = "INSERT INTO COMPRAS_ENC(PED_NRO, PED_LIN, MED_ID, CANT_COM, PRE_UNI) values" & _
    21.                                     "(@ped_nro, @ped_lin, @med_id, @cant_com, @pre_uni)"
    22.  
    23.            
    24.             For Each row As DataGridViewRow In grid1.Rows
    25.  
    26.                 Dim sqlQry2 As New SqlClient.SqlCommand(sql2, sqlCon)
    27.                 With sqlQry2.Parameters
    28.                     .AddWithValue("@ped_nro", txtNumShop.Text)
    29.                     .AddWithValue("@ped_lin", row.Cells(0).Value)
    30.                     .AddWithValue("@med_id", row.Cells(1).Value)
    31.                     .AddWithValue("@cant_com", row.Cells(2).Value)
    32.                     .AddWithValue("@pre_uni", row.Cells(3).Value)
    33.                 End With
    34.  
    35.                 sqlQry2.ExecuteNonQuery()
    36.             Next
    37.  
    38.             sqlQry.ExecuteNonQuery()
    39.             sqlCon.Close()
    40.  
    41.         Catch ex As Exception
    42.             MessageBox.Show(ex.Message)
    43.  
    44.         End Try
    45.         'Me.Close()
    46.  
    47.     End Sub

  20. #20

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    it shows me an error but when i go to my database the values were saved.
    Prepared statement’(@ped_nro nvarchar(5), @ped_lin nvarchar(4000),@med_id nvarchar(4’ expects parameter @ped_lin, which was not supplied

  21. #21

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    the datatypes are:
    PED_NRO = VARCHAR 10
    PED_FCH = VARCHAR 12
    PROV_ID = VARCHAR 10
    TIP_COMPRA = CHAR 10

    PURCHASE DETAILS:
    PED_NRO = VARCHAR 10
    PED_LIN = NUMERIC 9
    MED_ID = VARCHAR 10
    CANT_COM = NUMERIC 9
    PRE_UNI = NUMERIC 9

  22. #22
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    Try this:

    vb.net Code:
    1. Private Sub cmdAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAceptar.Click
    2.         Try
    3.  
    4.             Const CCon As String = "data source = DATASERVER;Initial Catalog= CATV;user id = sa;password=sa"
    5.             Dim sqlCon As New Data.SqlClient.SqlConnection(CCon)
    6.  
    7.             Dim Sql As String = "INSERT INTO COMPRAS_ENC(PED_NRO, PED_FCH, PROV_ID, TIP_COMPRA) Values " & _
    8.                                     "(@ped_nro, @ped_fch, @prov_id, @tip_compra)"
    9.  
    10.             Dim sqlQry As New SqlClient.SqlCommand(Sql, sqlCon)
    11.  
    12.  
    13.             With sqlQry.Parameters
    14.                 .AddWithValue("@ped_nro", txtNumShop.Text)
    15.                 .AddWithValue("@ped_fch", dtpFecha.Text)
    16.                 .AddWithValue("@prov_id", cboCodProv.Text)
    17.                 .AddWithValue("@tip_compra", cboCompra.Text)
    18.             End With
    19.  
    20.             sqlCon.Open()
    21.             Dim sql2 As String = "INSERT INTO COMPRAS_ENC(PED_NRO, PED_LIN, MED_ID, CANT_COM, PRE_UNI) values" & _
    22.                                     "(@ped_nro, @ped_lin, @med_id, @cant_com, @pre_uni)"
    23.  
    24.            
    25.             For Each row As DataGridViewRow In grid1.Rows
    26.  
    27.                 Dim sqlQry2 As New SqlClient.SqlCommand(sql2, sqlCon)
    28.                 With sqlQry2.Parameters
    29.                     .AddWithValue("@ped_nro", txtNumShop.Text)
    30.                     .AddWithValue("@ped_lin", ToDecimal(row.Cells(0).Value.ToString))
    31.                     .AddWithValue("@med_id", row.Cells(1).Value.ToString)
    32.                     .AddWithValue("@cant_com", ToDecimal(row.Cells(2).Value.ToString))
    33.                     .AddWithValue("@pre_uni", ToDecimal(row.Cells(3).Value.ToString))
    34.                 End With
    35.  
    36.                 sqlQry2.ExecuteNonQuery()
    37.             Next
    38.  
    39.             sqlQry.ExecuteNonQuery()
    40.             sqlCon.Close()
    41.  
    42.         Catch ex As Exception
    43.             MessageBox.Show(ex.Message)
    44.  
    45.         End Try
    46.         'Me.Close()
    47.  
    48.     End Sub
    49.  
    50.     Private Function ToDecimal(ByVal value As String) As Decimal
    51.         Dim fp As IFormatProvider = Globalization.NumberFormatInfo.CurrentInfo
    52.         ' Will throw an exception if conversion fails. Catch it in the main sub
    53.         Dim ret As Decimal = Decimal.Parse(value, fp)
    54.         Return ret
    55.     End Function

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    object reference no set to an instance of an object. this error it's now showing

  24. #24
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    Quote Originally Posted by jess21 View Post
    object reference no set to an instance of an object. this error it's now showing
    On what?

  25. #25

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    when i clicked the save button

  26. #26

  27. #27

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    noneone, but when i go to my database the values were saved

  28. #28

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i comment the try, catch and end try to see in what line is the error. it's in the line of the first row of the datagrid
    .AddWithValue("@ped_lin", ToDecimal(row.Cells(0).Value.ToString))

  29. #29
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    This is probably because your datagridview contains empty cells.

    Change the inner cycle code to this one:

    vb.net Code:
    1. For Each row As DataGridViewRow In grid1.Rows
    2.  
    3.     Dim sqlQry2 As New SqlClient.SqlCommand(sql2, sqlCon)
    4.  
    5.     Dim values() As String = {"0", "", "0", "0"}
    6.  
    7.     For i As Integer = 0 To 3
    8.         If Not (IsNothing(row.Cells(i).Value) OrElse IsDBNull(row.Cells(i).Value)) Then
    9.             values(i) = row.Cells(0).Value.ToString
    10.         End If
    11.     Next
    12.  
    13.     With sqlQry2.Parameters
    14.         .AddWithValue("@ped_nro", txtNumShop.Text)
    15.         .AddWithValue("@ped_lin", ToDecimal(values(0)))
    16.         .AddWithValue("@med_id", values(1))
    17.         .AddWithValue("@cant_com", ToDecimal(values(2)))
    18.         .AddWithValue("@pre_uni", ToDecimal(values(3)))
    19.     End With
    20.  
    21.     sqlQry2.ExecuteNonQuery()
    22. Next

  30. #30

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i have problems with the foreign key med_id, i changed to the previous value (.AddWithValue("@med_id", row.Cells(1).Value)) and i delete a value form values array. but i have the same error message. I don't know if it's not taking the datagridcomboxcolumn (med_id). But remember it save them into my db, it's just only the message

  31. #31
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    To be perfectly honest, I don't understand your last post, particularly this part: 'i delete a value form values array'.

    The code in the post #29 should work. I think I have tied all loose ends. I simply have no idea why you keep receiving this error message.

    Have you tried tracing your code? Do you know how to do it? If not, have a look at this:
    http://www.homeandlearn.co.uk/net/nets5p6.html

    Try to step through the code line by line and perhaps you will be able to isolate the problem.

  32. #32

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    i used breakpoints and it's taking the last row of the datagrid that it's empty

  33. #33
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: save datagridview multiple rows

    Then use this

    Code:
    Dim r As Integer, row As DataGridViewRow
    
    For r = 0 To grid1.Rows.Count - 2 ' Normally it would be - 1 but if the last row is empty then we use one row less
        row = grid1.Rows(r)
        
        Dim sqlQry2 As New SqlClient.SqlCommand(sql2, sqlCon)
    
        Dim values() As String = {"0", "", "0", "0"}
    
        For i As Integer = 0 To 3
            If Not (IsNothing(row.Cells(i).Value) OrElse IsDBNull(row.Cells(i).Value)) Then
                values(i) = row.Cells(0).Value.ToString
            End If
        Next
    
        With sqlQry2.Parameters
            .AddWithValue("@ped_nro", txtNumShop.Text)
            .AddWithValue("@ped_lin", ToDecimal(values(0)))
            .AddWithValue("@med_id", values(1))
            .AddWithValue("@cant_com", ToDecimal(values(2)))
            .AddWithValue("@pre_uni", ToDecimal(values(3)))
        End With
    
        sqlQry2.ExecuteNonQuery()
    Next

  34. #34

    Thread Starter
    Lively Member
    Join Date
    Apr 2010
    Posts
    69

    Re: save datagridview multiple rows

    that's work good to me. If you remember i used a variable to go to each row of my datagrid but i count the rows - 1, i tryed with -2 before (like post 1) 'cause i see a tread with teh same problem.
    Anyway, Thanks again

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width