简体   繁体   English

更新数据表中的行

[英]Update row in datatable

I'm trying to update a row in my datatable depending on its ID. 我正在尝试根据其ID更新数据表中的一行。 The data i'm inserting are from sql. 我要插入的数据来自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

Figured it out! 弄清楚了! :) :)

I used the following code to search in my datatable using a dynamic value 我使用以下代码使用动态值在数据表中进行搜索

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM