Can anyone explain exactly why Method 1 in the following code does not alter the DataTable where the other 2 methods do?
It’s obviously some kind of referencing issue, but why exactly?
Imports System
Imports System.Data
Public Class Test
Public Shared Sub Main()
'Build Table
Dim dt as New DataTable
dt.Columns.Add("ID",GetType(String))
dt.Columns.Add("Name",GetType(String))
'Populate Table
Dim dr as DataRow
dr = dt.NewRow()
dr("ID")="Man" : dr("Name") = "mike" : dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID")="Man" : dr("Name") = "ian" : dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID")="Man" : dr("Name") = "rob" : dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID")="Woman" : dr("Name") = "ann" : dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID")="Woman" : dr("Name") = "sam" : dt.Rows.Add(dr)
output(dt) 'Output Table
Dim drFilters() as DataRow = dt.Select("ID='Man'") 'Select all Man
'Method 1 does not change dt
'dr = dt.NewRow()
'dr("ID")="cowman" : dr("Name")="bugle"
'drFilters(1)=dr
'Method 2 does change dt
dr = drFilters(1)
dr("ID")="cowman" : dr("Name")="bugle"
'Method 3 does change dt
'drFilters(1)("ID")="cowman" : drFilters(1)("Name")="bugle"
output(dt) 'Output final table
End Sub
Public Shared Sub output(dt as DataTable)
for each dr as DataRow in dt.Rows
Console.WriteLine(dr("ID") + vbTab + dr("Name"))
Next
Console.WriteLine("")
End Sub
End Class
Apologies for the stupid test data 🙂
When you call
drFilters(1)=dr, you have replaced theDataRowreference in the filter collection, which is a separate collection from the row references in theDataTableitself.dt.Rowsis a list of references toDataRowobjects, as isdrFilters(), but changing an entry in one list of references does not in any way affect the other list of references.After the call to
drFilters(1)=dr, the collections look like thisNote that
dt.Rowsis left unchanged. However, when you retrieve the objectdrFilters(1)and make changes to that, you have a reference directly todt.Rows(1), so changes to its properties are reflected in the output ofdt.Hope this helps!