prameela rani prameela rani - 4 months ago 49
Vb.net Question

Update datatable row with its row index vb.net

I have a DataTable with column

DisplayOrder
. 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
DisplayOrder
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))

Answer

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
   Next
End If

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