prameela rani prameela rani - 5 months ago 62 Question

Update datatable row with its row index

I have a DataTable with column

. It maintains incremented values by 1 per Entity Column. In few scenarios this increment will disturb. Now I need to update the DataTable to maintain the
column value by 1.

I have tried following code. but it updates all rows by 1.

Dim i As Integer = 0

dtCustomers.Select("EntityID =" & EntityID).ToList().ForEach(Function(r) InlineAssignHelper(r("DisplayOrder"), i))


I assume that your InlineAssignHelper takes the second parameter and tries to set the value for the column DisplayOrder. But as you have written this code that is not possible because you pass the VALUE of the column DisplayOrder for the current row and not the row itself. Moreover you need to increment the value of i otherwise you set always the value zero fixed outside the call to DisplayOrder.

For all this reasons (and also for more readability) I recommend to leave the ForEach list extension and use a traditional loop

Dim rows = dtCustomers.Select("EntityID =" & EntityID)
if rows IsNot Nothing Then
   For x = 0 to rows.Length - 1
      InlineAssignHelper(rows(x), "DisplayOrder", x+1))
      ' At this point you can also directly set the column without an helper function
      ' rows(x)("DisplayOrder") = x+1
End If

Public Sub InlineAssignHelper(row As DataRow, colName as String, value As Integer)
     row(colName) = value
End Sub