Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dim TDate As Date
            Dim Batch As String
            Dim Product As String
            Dim Code As String
            Dim Material As String
            Dim Quantity As String
            For i As Integer = 0 To DataGridView1.Rows.Count - 1
                TDate = DataGridView2.Rows(i).Cells(0).Value
                Batch = DataGridView1.Rows(i).Cells(1).Value
                Product = DataGridView1.Rows(i).Cells(2).Value
                Code = DataGridView1.Rows(i).Cells(3).Value
                Material = DataGridView1.Rows(i).Cells(4).Value
                Quantity = DataGridView1.Rows(i).Cells(5).Value
                con.Open()
                sql = "INSERT INTO Material_consumption(TDate, Batch, Product_name, Material_code, Material_name, Quantity) VALUES(?,?,?,?,?,?)"
                Dim cmd As New OleDb.OleDbCommand(sql, con)
                ' cmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@TDate", TDate))
                '  cmd.Parameters.Add(New System.Data.OleDb.OleDbParameter("@Batch", Batch))
                cmd.Parameters.AddWithValue("@TDate", TDate)
                cmd.Parameters.AddWithValue("@Batch", Batch)
                cmd.Parameters.AddWithValue("@Product_name", Product)
                cmd.Parameters.AddWithValue("@Material_code", Code)
                cmd.Parameters.AddWithValue("@Material_name", Material)
                cmd.Parameters.AddWithValue("@Quantity", Quantity)
                cmd.ExecuteNonQuery()
                ' cmd.Dispose()

            Next
            con.Close()
             MessageBox.Show("Registered Successfully!", "Register", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Catch ex As OleDb.OleDbException
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Oledb Error")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try

        MessageBox.Show("Records inserted.")


What I have tried:

I have written the following code for insert data from dbgridview to database in access. I get problem Index was out of range. Please suggest me the solution. I have written in VB
Posted
Updated 27-May-20 19:52pm

1 solution

Quote:
I get problem index was out of range.

Error message also tells you the position of error (line number), it helps to spot the problem.
Are you sure that DataGridView2 have at least same number of rows than DataGridView1 ?
VB
For i As Integer = 0 To DataGridView1.Rows.Count - 1
    TDate = DataGridView2.Rows(i).Cells(0).Value
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900