Quantcast
Channel: VBForums - Visual Basic 6 and Earlier
Viewing all articles
Browse latest Browse all 21868

[RESOLVED] .AddNew won't create new key

$
0
0
It's a long story, but the long and short is, I'm trying to rewrite my latest project. My computer went in for repair and they had to reformat the HDD. When I restored my data from the backup, all, and I mean ALL my vb projects, forms and .exe's had disappeared. The folder was still there and so were the pictures I had for various apps I had written over the years. My intention was to rewrite in vb.net but I'm finding it very slow and laborious. Since I need this project ASAP, I decided to reinstall VB6 and start again.
I have a problem with .AddNew. I get the error message "The requested changes were not carried out correctly because it would create a duplicate index, key or relation. Change the data in the field or fields that contain duplicate data, remove the index or re-define the index to allow duplicates and try again.
The Table only has 2 fields.
Field(0) is the Key field, defined as Long
Field(1) is the name of the group, defined as String
it fails on the highlighted line, following the .AddNew
field(1) is set correctly to the group name but, when I did
?.Field(0) in the immediate window, it showed 0
The file is empty at the moment but it did the same with a record already created.
Code:

Private Sub cmdAdd_Click()
Dim sSQL As String

    If txtGroupName = "" Then
        MsgBox "You must enter a group name to add.", vbCritical, "Error"
        txtGroupName.SetFocus
        cmdDelete.Visible = True
        Exit Sub
    End If
    OpenFile
    sSQL = "SELECT * FROM tblGroup WHERE grName='" & txtGroupName.Text & "'"
    With rs
        .Open sSQL, cn, adOpenKeyset, adLockPessimistic, adCmdText
        If .RecordCount > 0 Then
            MsgBox "This group already exists.", vbCritical, "Error"
            .Close
            cmdDelete.Visible = True
            Exit Sub
        End If
        .Close
        OpenFile
        .Open "tblGroup", cn, adOpenKeyset, adLockPessimistic, adCmdTable
        .AddNew
        .Fields("grName").Value = txtGroupName.Text
        .Update
        .Close
        MsgBox "Group " & txtGroupName.Text & " added correctly", vbOKOnly, "Success"
        txtGroupName.Text = ""
        cmdDelete.Visible = True
    End With
End Sub

And in the module:
Code:

Public cn As ADODB.Connection
Public rs As ADODB.Recordset

Public Sub OpenFile()
    Set cn = New ADODB.Connection
    cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                        "Data Source=" & App.Path & "\Student.mdb;Persist Security Info=False"
    cn.Open
    Set rs = New ADODB.Recordset
End Sub


Viewing all articles
Browse latest Browse all 21868

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>