List of VB.Net objects unexpectedly cleared after error

This may be a pretty fundamental problem with the way I wrote this, but I need help: I ​​have an uncertainty defined as an open class with two fields, both lines

Public Class mp Dim _fg As String Dim _scode As String Property fg As String Get Return _fg End Get Set(ByVal value As String) _fg = value End Set End Property Property scode As String Get Return _scode End Get Set(ByVal value As String) _scode = value End Set End PropertyEnd Class 

Then I define an array of them:

 Dim mps As New List(Of mp)() 

Then in the loop, I start adding to the list after it’s first cleared:

  Dim mpholder As New mp cmd.CommandText = 'Query here cmd.ExecuteNonQuery() reader = cmd.ExecuteReader mp.Clear() Try Do While reader.Read() mpholder.fg = "" mpholder.scode = "" mpholder.fg = reader(0) mpholder.scode = reader(1) mps.Add(mpholder) Loop Catch ex As Exception MP_Res.Text = "error" End Try 

If at some stage I get an error and get a catch, the "mp" list has the same number of entries, but they are all empty

+4
source share
2 answers

You continue to add the same item to the list.

Try moving the line

 Dim mpholder As New mp 

in the read / add loop:

 Do While reader.Read() Dim mpholder As New mp mpholder.fg = reader(0) mpholder.scode = reader(1) mps.Add(mpholder) Loop 

Since mp declared as a class , this means that the reference type, that is, variables of type mp , are not the objects themselves, but are only references to them. Therefore, if I do this:

 Dim mp1 As New mp Dim mp2 = mp1 

I would not have two mp objects, I would have two links to one mp object. And if I change one property of the object, this change will be visible through each of the links.

 mp1.fg = "Test" mp2.fg = "Test2"; Console.WriteLine(mp1.fg) ' "Test2" 
+2
source

Try the above. You just need to create your object in a loop.

  cmd.CommandText = 'Query here cmd.ExecuteNonQuery() reader = cmd.ExecuteReader Try Do While reader.Read() Dim mpholder As New mp mpholder.fg = reader(0) mpholder.scode = reader(1) mps.Add(mpholder) Loop Catch ex As Exception MP_Res.Text = "error" End Try 
+1
source

Source: https://habr.com/ru/post/1497813/


All Articles