问题
this question is based on this Link
I haven't found an answer, but I am trying on a solution and resulted to another question..
Public Class markerRow
Public MarkerName As String
Public CameraID As Integer
Public HostAddress As String
End Class
Public mr As New markerRow
Dim aList As New List(Of markerRow)
For Each dtrow In markerDtable.Rows
mr.MarkerName = dtrow("MarkerName")
mr.CameraID = dtrow("CameraID")
mr.HostAddress = dtrow("HostAddress")
aList.Add(New markerRow())
Next
from what I think, this code should add every data from the DB to the respective variables in the list.. But I still don't know what it does exactly.
I checked the aList.Count.ToString
and it gave me 5 items, which is true since I have 5 rows in my DB..
For Each elem In aList
listbox.Items.Add(mr.MarkerName)
listbox.Items.Add(mr.CameraID)
Next
to check what items are in the aList
, I did that.. unfortunately.. it only gives me the last item, 5 times. the last item on MarkerName Column and Camera ID Column.
What am I missing? or what's wrong in my code?
the aList
should have what's on the DB above. not only the last item.
回答1:
Public mr As New markerRow
Dim aList As New List(Of markerRow)
For Each dtrow In markerDtable.Rows
mr.MarkerName = dtrow("MarkerName")
mr.CameraID = dtrow("CameraID")
mr.HostAddress = dtrow("HostAddress")
aList.Add(New markerRow())
Next
Here, you are creating one markerRow
named mr
, and update it for every row in the DataTable
. Also, for every row, you create another markerRow
, and add that new one to aList
.
For Each elem In aList
listbox.Items.Add(mr.MarkerName)
listbox.Items.Add(mr.CameraID)
Next
Then, for each element in aList
, you add two items to the ListBox
, and everytime it's MarkerName
and CameraID
from mr
, and not the data from the elements of aList
.
You're probably looking for something like:
Dim aList As New List(Of markerRow)
For Each dtrow In markerDtable.Rows
Dim mr = New markerRow() ' create a new markerRow for every row '
mr.MarkerName = dtrow("MarkerName")
mr.CameraID = dtrow("CameraID")
mr.HostAddress = dtrow("HostAddress")
aList.Add(mr) ' add the new markerRow to the list '
Next
For Each elem In aList
listbox.Items.Add(elem.MarkerName)
Next
来源:https://stackoverflow.com/questions/20513686/why-doesnt-it-add-to-the-list