how to save records in listview into ms access database table using a button , i've tried with my codes but nothing is saved in the database

`Inline Code Example Here`

private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim con As New OleDbConnection
    con.ConnectionString = "Provider= microsoft.jet.oledb.4.0; data source = ..\Jualan.mdb"
    Dim cmd As New OleDbCommand()
    InitializeComponent()
    con.Open()
    For i As Integer = 0 To ListView1.Items.Count - 1
        Dim query As String = "INSERT INTO Jual VALUES (No_resit, Kod_produk, Nama_produk, Harga, Kuantiti, Tarikh, Sub_total)"
        cmd = New OleDbCommand(query, con)
        cmd.Parameters.Add("No_resit", OleDbType.[Integer]).Value = (ListView1.Items(i).SubItems(1).Text)
        '!!
        cmd.Parameters.Add("Kod_produk", OleDbType.VarChar, 50).Value = ListView1.Items(i).SubItems(2).Text
        cmd.Parameters.Add("Nama_produk", OleDbType.VarChar, 50).Value = ListView1.Items(i).SubItems(3).Text
        cmd.Parameters.Add("Harga", OleDbType.VarChar, 50).Value = ListView1.Items(i).SubItems(4).Text
        cmd.Parameters.Add("Kuantiti", OleDbType.VarChar, 50).Value = ListView1.Items(i).SubItems(5).Text
        '!!
        cmd.Parameters.Add("Tarikh", OleDbType.VarChar, 50).Value = ListView1.Items(i).SubItems(0).Text
        ' !!
        cmd.Parameters.Add("Sub_total", OleDbType.VarChar, 50).Value = ListView1.Items(i).SubItems(6).Text
        ' !!
        cmd.ExecuteNonQuery()
        con.Close()
    Next


    cmd.Dispose()

End Sub

End Class

I created a listview with three columns for FirstName, LastName and Age. To insert all rows of the listview into mytable I could code

For Each row As ListViewItem In ListView1.Items
    Dim query As String = "insert into mytable (FirstName,LastName,Age) Values(" &
                          "'" & row.SubItems(0).Text & "'," &
                          "'" & row.SubItems(1).Text & "'," &
                                row.SubItems(2).Text &
                          ")"
    'execute query here
    Debug.WriteLine(query)
Next

Naturally, you would execute the query instead of writing the query to the debug output. This code does no error checking (Try/Catch) for possible problems like duplicate records, etc. Note that in the database, the first two fields would be stared as strings and the third as a number. That is why the third field does not have single quotes around it in the query.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.