1

I have been trying to write a program for a company that I work for, that would do assist tracking as well as give an overview of where the assists are.

The idea is to have a database with unique numbers on them that is allocated to all the hardware.

When a "desk" button is pressed it will show the info form that desk and it can be edited from there.

I roughly have what I was looking for, but I'm struggling with an issue when I update data, the data is somehow placed in the incorrect row...

E.g:

Desk Name : TL1 PC : 0001 monitor : 0002

Desk Name : TL2 PC : 0003 monitor : 0004

If I update the fist data entry alone it works fine.. however when I update the second entry it gets saved onto the first entry

E.g:

Desk Name : TL2 PC : 0003 monitor : 0004

Desk Name : TL2 PC : 0003 monitor : 0004

This is the code I have so far, any help would be very appreciated.

Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Dim inc As Integer


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'Lib_9th_NLDataSet.tblContacts' table. You can move, or remove it, as needed.
    Me.TblContactsTableAdapter.Fill(Me.Lib_9th_NLDataSet.tblContacts)

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = \\elite03\IT\Assets\Lib 9th NL.mdb"

    con.ConnectionString = dbProvider & dbSource

    con.Open()


    sql = "SELECT Desk,Pc,Monitor,Keyboard,Phone,Laptop FROM tblcontacts"
    da = New OleDb.OleDbDataAdapter(sql, con)
    da.Fill(ds, "Lib_9th_NL")



    con.Close()
    MaxRows = Lib_9th_NLDataSet.tblContacts.Rows(inc).Item(inc)
    inc = 0


End Sub

Private Sub NavigateRecords()


    txtDesk_Name.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(0)
    txtPC.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(1)
    txtMonintor.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(2)
    txtKeyboard.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(3)
    txtPhone.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(4)
    txtlaptop.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(5)

End Sub

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click

    Me.Validate()
    Me.TblContactsBindingSource.EndEdit()
    Me.TableAdapterManager.UpdateAll(Me.Lib_9th_NLDataSet)

End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click


    If inc <> MaxRows - 0 Then

        inc = inc + 1

        NavigateRecords()

    Else
        MsgBox("No More Rows")

    End If
End Sub

Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
    If inc > 0 Then

        inc = inc - 1

        NavigateRecords()

    Else

        MsgBox("First Record")

    End If

End Sub

Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
    btnCommit.Enabled = True
    btnUpdate.Enabled = False
    btnDelete.Enabled = False
    btnAddNew.Enabled = False


    txtDesk_Name.Clear()
    txtPC.Clear()
    txtMonintor.Clear()
    txtKeyboard.Clear()
    txtPhone.Clear()
    txtlaptop.Clear()
End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
    btnCommit.Enabled = False
    btnAddNew.Enabled = True
    btnUpdate.Enabled = True
    btnDelete.Enabled = True

    inc = 0

    NavigateRecords()
End Sub

Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
    If inc <> -1 Then

        Dim cb As New OleDb.OleDbCommandBuilder(da)
        Dim dsNewRow As DataRow

        dsNewRow = ds.Tables("Lib_9th_NL").NewRow()


        dsNewRow.Item("desk") = txtDesk_Name.Text
        dsNewRow.Item("PC") = txtPC.Text
        dsNewRow.Item("Monitor") = txtMonintor.Text
        dsNewRow.Item("Keyboard") = txtKeyboard.Text
        dsNewRow.Item("Phone") = txtPhone.Text
        dsNewRow.Item("Laptop") = txtlaptop.Text

        ds.Tables("Lib_9th_NL").Rows.Add(dsNewRow)

        da.Update(ds, "Lib_9th_NL")

        MsgBox("New Record added to the Database")


        btnCommit.Enabled = False
        btnAddNew.Enabled = True
        btnUpdate.Enabled = True >
        btnDelete.Enabled = True

    End If
End Sub

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then

        MsgBox("Operation Cancelled")
        Exit Sub

    End If

    Dim cb As New OleDb.OleDbCommandBuilder(da)

    ds.Tables("Lib_9th_NL").Rows(inc).Delete()
    MaxRows = MaxRows - 1

    inc = 0

    da.Update(ds, "Lib_9th_NL")
    NavigateRecords()
End Sub

Private Sub TL1_Click(sender As Object, e As EventArgs) Handles TL1.Click
    txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(1)
    txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(2)
    txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(3)
    txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(4)
    txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(5)
    txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(6)
End Sub

Private Sub Ret1_Click(sender As Object, e As EventArgs) Handles Ret1.Click
    txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(1)
    txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(2)
    txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(3)
    txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(4)
    txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(5)
    txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(6)
End Sub

End Class
Dmitry Pavliv
  • 34,126
  • 12
  • 75
  • 77
Terick
  • 13
  • 3
  • How are you "updating"? Are these all just text fields on a form? How are you telling the code executed on `btnUpdate` which record to update? I would assume the problem is arising in the line `Me.TableAdapterManager.UpdateAll(Me.Lib_9th_NLDataSet)` – Mark C. Apr 17 '14 at 12:41
  • I am updating it using a button Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click Me.Validate() Me.TblContactsBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me.Lib_9th_NLDataSet) End Sub – Terick Apr 17 '14 at 13:01
  • Maybe try to replace `.UpdateAll()` to `.Update(Me.Lib_9th_NLDataSet.tblContacts)`. I've never used TableAdapterManager, so I am guessing here. – Mark C. Apr 17 '14 at 13:17
  • Will give it a shot, thanks man – Terick Apr 17 '14 at 13:18
  • No problem.. Let me know how it turns out. – Mark C. Apr 17 '14 at 13:19
  • It gave a value error when I used Update(Me.Lib_9th_NLDataSet.tblContacts) with the TableAdapterManager so I changed it to the Me.TblContactsTableAdapter.Update instead, it excepted the code but still have the same issue with row 0 being updated – Terick Apr 17 '14 at 13:44
  • Can I ask why you aren't using SQL to update in the database? – Mark C. Apr 17 '14 at 13:55
  • Well the database is created in MS Access and I have not dealt with a SQL database before. – Terick Apr 17 '14 at 14:00
  • So, basically - You want to take what the user types into text boxes and update fields in a table in your database appropriately? – Mark C. Apr 17 '14 at 14:01
  • Yeah that is exactly what I am trying to achieve. – Terick Apr 17 '14 at 14:05
  • Let me paste in an answer how I do this. I think it will be very clear. – Mark C. Apr 17 '14 at 14:06
  • Awesome, and thanks again for the help – Terick Apr 17 '14 at 14:09

1 Answers1

1

It seems like you might be getting mixed up between your DataSet and your TableAdapterManager.

First, we need to get the values from the text boxes.

            empID = EmployeeIDTxt.Text
            dob = DateOfBirthTxt.Text
            mailStation = MailStationTxt.Text
            eFirst = FNameTxt.Text
            prefName = PrefNameTxt.Text
            eLast = LNameTxt.Text
            homeAddress = Address1Txt.Text
            city = CityTxt.Text
            state = StateTxt.Text
            zip = ZipTxt.Text
            payGroup = PayGroupTxt.Text
            fileNo = FileNoTxt.Text
            begDT = BegDtTxt.Text

Now, we can reference the fields in our Update query as variables, and add parameters to them so we can prevent SQL Injection.

     'This is your update statement
     Dim updateQry As String = String.Empty 
     updateQry = "UPDATE YOURTABLE"
     updateQry &= " SET  EMPL_ID = @EmployeeID,EMPL_LAST_NM = @LastName, EMPL_FIRST_NM = @FirstName, EMPL_PREFRD_NM = @PrefName,"
     updateQry &= "      EMPL_BIRTH_DT = @DateOfBirth, EMPL_MAIL_STN_CD = @MS, EMPL_ADDR1_TXT = @HomeAddress,"
     updateQry &= "       EMPL_ADDR2_TXT = @Add2, EMPL_CITY_NM = @City, EMPL_STATE_CD = @State, EMPL_POSTL_CD = @Zip,"
     updateQry &= " WHERE EMPL_ID = @EmployeeID ;"

     'Declare Connection String
      Using sqlConnection As New OleDBConnection(myConn)
         Using cmd As New OleDBCommand()
             'Declare variable for SQL command
                With cmd
                   .Connection = sqlConnection
                   .CommandType = CommandType.Text
                   .CommandText = updateQry
                   'Prevent against SQL Injection -> Add Parameters
                     With .Parameters
                        .AddWithValue("@EmployeeID", empID)
                        .AddWithValue("@FirstName", eFirst)
                        .AddWithValue("@LastName", eLast)
                        .AddWithValue("@PrefName", prefName)
                        .AddWithValue("@DateOfBirth", dob)
                        .AddWithValue("@MS", mailStation)
                        .AddWithValue("@HomeAddress", homeAddress)
                        .AddWithValue("@City", city)
                        .AddWithValue("@State", state)
                        .AddWithValue("@Zip", zip)
                     End With
                End With

                Try
                    sqlConnection.Open()
                    cmd.ExecuteNonQuery()
                Catch ex As Exception
                    MessageBox.Show("Error Updating " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End Using
       End Using
   End If
Catch ex As Exception
    MsgBox(ex.Message)
 Finally
    MsgBox("" & FNameTxt.Text & " " & LNameTxt.Text & " has been updated")
End Try

Now, we need to change a few things.

  1. Replace myConn with your connection string and open it in this instance (in the btnUpdate sub)
  2. Change all of the fields in the Parameter list to your variables. ("EmployeeID" is the parameter I am providing for the variable empID)
  3. Your WHERE clause is going to depend on what records you want to update. That's for you to decide. Is there a primary key you can reference like I do with EmployeeID?

Replace EMPL_ fields with your field names. For clarification, the "@EmployeeID" parameter is the safe way of writing to the database of adding empID directly.

There are a couple other ways to do this, such as OleDbUpdateCommand, etc.

Hope this helps you.

Community
  • 1
  • 1
Mark C.
  • 5,789
  • 4
  • 31
  • 60
  • Thanks for the trouble, I will do it and let you know of out come. Really hope I can get it working. And to answer you yes the is an primary key on the ID however did not import it as I thought the key is one of the issues I might be having. – Terick Apr 17 '14 at 14:51
  • It is easily solvable, I just don't know enough about what you're doing to assist you more. – Mark C. Apr 17 '14 at 14:52
  • Tired to add a screen shot of the form lay out, but I am not popular enough :D – Terick Apr 17 '14 at 15:01
  • It's okay. Just try what you see and if you have any questions, first try to figure it out, but if it's dire and you're blue in the face then ask me. – Mark C. Apr 17 '14 at 15:06
  • Hey Newbie, Thanks for your help. It has put me on the correct path that I need to be and managed to find my error. Your update statement worked great but here is the issue and perhaps you can help me once again... basically if I use the datagridview and update it from there is works but the I need to make a button to select a specific row in the datagrid and then update it. reason for this is on the form the datagridview is not going to be there but instead buttons that displays the data and selects the rows. – Terick Apr 22 '14 at 13:01
  • I think you need to evaluate on how you're going to select which row you want to update. Is there going to be a button at the end of each row (I am thinking this is not the case because of what you said) or how is the user going to know which row the button is going to interact with? – Mark C. Apr 22 '14 at 13:06
  • The user will know which row by the naming convention used for the buttons, using this code is more or less what I think I need DataGridView1.Rows(1).Selected = True.. the issue is though it does not go the row it highlights it. – Terick Apr 22 '14 at 13:14
  • I'm really not sure I know the correct answer. So you have a button that says Update First Row or something? – Mark C. Apr 22 '14 at 13:21
  • No, the database is updating fine. But it only updates the first row because the second row is not selected... This is a explanation of the form lay out. on the left there is 6 textboxes that display the data E.g Desk: Ret1 PC:0001 Monitor:0002 ect and on the right side of the form is 11 buttons with unique names e.g Ret1.. now here is the problem. when I select any of the buttons it displays the correct info form the database, but when trying to update any of the "buttons" besides the Ret1 (because it is index 0) it updates the first row only.. it does not go to any other row. – Terick Apr 22 '14 at 13:39
  • Yes. so what do you want to happen? You said the button is going to designate what row is going to be updated? Do you want all the rows to be updated? What is your question exactly? – Mark C. Apr 22 '14 at 13:44
  • So basically I need a command that would go to that specific row on the database. like DataGridView1.Rows(1).Selected = True but Like I said it only highlights it, it does not actually go the row that I need it to go to – Terick Apr 22 '14 at 13:45
  • I think you would need `.CurrentRow = DataGridView1.Rows(1)` or something like that. – Mark C. Apr 22 '14 at 13:56
  • Hi Newbie, thanks again for all your help. the code was DataGridView1.CurrentCell = DataGridView1.Rows(0).Cells(0) that I needed. Can you mark the question answered please? – Terick Apr 22 '14 at 14:39
  • Ah, yes. That was my suggested code but you said you wanted the row, not the first cell of the first row. Anyway, you're welcome. I'm glad you got it figured out. To mark the question as answered, you click the green check mark at the top of my answer to the left. – Mark C. Apr 22 '14 at 14:41
  • Did not know I needed the cell as well, still a noob ;) you are awesome! – Terick Apr 22 '14 at 14:53
  • 1
    Not awesome, I have just done it before. Now you know! Good luck with the rest of your app/project. – Mark C. Apr 22 '14 at 14:54