user3194603
user3194603

Reputation: 31

Update row in datatable

I'm trying to update a row in my datatable depending on its ID. The data i'm inserting are from sql. I'm trying to prevent duplicates in the table and also if a duplicate occurs i want to increment the times column. This is my code. Whenever i execute it i get this error : Additional information: Index was outside the bounds of the array. It looks to me that the select cant find the correct row in the datatable. Any suggestions?

Dim listID As New List(Of Integer)
Dim dt As New DataTable
dt.Columns.Add("LOID")
dt.Columns.Add(New DataColumn("Correct", GetType(Integer)))
dt.Columns.Add(New DataColumn("Times", GetType(Integer)))

For Each dr As DataRow In ds.Tables(0).Rows
    If Not listID.Contains(dr.Item("LOID")) Then
        'check if its correct
        Dim answerCorrect As Integer
        If dr.Item("Correct") = 1 Then
            answerCorrect = 1
        Else
            answerCorrect = 0
        End If
        'add new row
        listID.Add(dr.Item("LOID"))
        dt.Rows.Add(dr.Item("LOID"), answerCorrect, 1)
    Else
        'update table set times plus 1
        Dim myRow() As Data.DataRow
        Dim rowName As String = "LOID = " & dr.Item("LOID")
        myRow = dt.Select(rowName)

        Dim timesLO As Integer = myRow(0)("Times")
        myRow(0)("Times") = timesLO
        'update table depending if the answer is correct
        If dr.Item("Correct") = 1 Then
            myRow(0)("Correct") = myRow(0)("Correct") + 1
        End If

    End If
Next

Upvotes: 0

Views: 121

Answers (1)

user3194603
user3194603

Reputation: 31

Figured it out! :)

I used the following code to search in my datatable using a dynamic value

 myRow = dt.Select("LOID ='" & dr.Item("LOID") & "'")

Upvotes: 1

Related Questions