Link to home
Start Free TrialLog in
Avatar of 5281
5281

asked on

How to create a generic list and populate with database in asp.net (vb.net)

I need read a text file line by line (in a while loop), and compare the field in text file to the field in database.  I created a generic list and populated the database query into list.  I managed to make the code work.   However, the problem is how to change the code to open close database once instead of numerous time, because the file is being read line by line, it calls PopulateCustomer function when each line is read.  I used asp.net in vb.  


Public Class clsCustomer
   Private _CustomerID As String
   Private _Address As String
   Private _City As String

    Public Property CustomerID() As String

        Get
            Return _CustomerID
        End Get

        Set(ByVal value As String)
            _CustomerID = value
        End Set

    End Property
......
End Class



Public Function PopulateCustomer() As List(Of clsCustomer)

        Using con As SqlConnection = New SqlConnection(constring)
            Using cmd As SqlCommand = New SqlCommand("select CustomerID, Address, City from tblCustomer", con)
                con.Open()

                Using sdr As SqlDataReader = cmd.ExecuteReader

                    Dim GetCustomerInfo As New List(Of clsCustomer)

                    While sdr.Read

                        GetCustomerInfo.Add(New clsCustomer)
                        GetCustomerInfo(( GetCustomerInfo.Count - 1)).CustomerID = sdr("CustomerID").ToString
                        GetCustomerInfo(( GetCustomerInfo.Count - 1)).Address = sdr("Address").ToString
                        GetCustomerInfo(( GetCustomerInfo.Count - 1)).City = sdr("City").ToString
                       
                    End While
                    con.Close()

                    Return  GetCustomerInfo
                End Using
            End Using
        End Using
End Function



Public Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

 iRead = File.OpenText(myfile)
                While iRead.Peek <> -1                  
                    line = iRead.ReadLine()    'read input file line by line

 CustomerNum = Trim(Left(line, 20))      
 Address = Trim(Mid(line, 20, 50))      
 City = Trim(Mid(line, 50, 80))    

 Dim QueryCustomerID As List(Of clsCustomer) = (From c In PopulateCustomer() _        
                                            Where c.CustomerID = CustomerNum _
                                            Select c).ToList()


End While
iRead.close()
End Sub
ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 5281
5281

ASKER

Awesome.  Thank you.