Return several objects from a function

How do I return several objects from a function?

Page 1 of 1

6 Replies - 6699 Views - Last Post: 26 October 2008 - 04:18 PM Rate Topic: -----

#1 jens  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 67
  • View blog
  • Posts: 430
  • Joined: 09-May 08

Return several objects from a function

Posted 26 October 2008 - 06:39 AM

I have this function (below) that fetches posts from a database. At the moment I put each resulting post in a row that's part of a string. The string is returned by the function.

What I would like to do is to have a class that has the fields:
- ID (integer)
- Fnamn (string)
- Enamn (string)
- Fdatum (date)
and put each post from the DB in one such object. Then I want to put all these objects either in one object that holds all objects (which I believe is the better solution) OR in an array of objects. Then I want the function to return this object of objects (or array of objects).

I have tried a lot of different (obviously incorrect) ways of doing this and have not succseeded, thus the returning of a string.

I have a module named module1 where I put definitions that are needed in different parts of the app, I've tried to put a class definition in it. (code below).

The function that fetches posts:
Public Function ListaPersoner(ByVal enamn As String, ByVal e As System.EventArgs) As String
		Dim cno As New SqlConnection
		Dim cmd As New SqlCommand
		Dim rdr As SqlDataReader
		Dim rad As String
		Dim ant As Integer
		Dim command As New SqlCommand

		cno.ConnectionString = connString1
		cmd.Connection = cno
		cmd.Parameters.Add("@Enamn", SqlDbType.NChar, 10)
		cmd.Parameters("@Enamn").Value = enamn

		If enamn.Trim = "" Then
			cmd.CommandText = "SELECT * FROM namn ORDER BY Fnamn"
		Else
			cmd.CommandText = "SELECT * FROM namn where enamn like @Enamn ORDER BY Fnamn"
		End If

		cno.Open()
		ant = 0
		rad = ""
		rdr = cmd.ExecuteReader
		While rdr.Read
			ant += 1
			rad &= rdr.Item("ID").ToString.Trim & " "
			rad &= rdr.Item("Fnamn").ToString.Trim & " "
			rad &= rdr.Item("Enamn").ToString.Trim & " "
			rad &= rdr.Item("FDatum").ToString.Trim & vbCrLf
		End While
		Return rad
	End Function


A kind of class definition (totally wrong?):
Public Class personClass
	Public _Identitet As Integer
	Public _FörNamn As String
	Public _EfterNamn As String
	Public _Födelse As SqlTypes.SqlDateTime
End Class


Question:
How do I make the function return a bunch of objects that has the fields that are in the personClass above?

Thanks
/Jens

PS: Any improvements of the supplied code will be appreciated (e.g. try-catch-finally).
PPS: I do not want to use data set and/or datagridwiew at this time.

This post has been edited by jens: 26 October 2008 - 06:43 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Return several objects from a function

#2 dbasnett  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 109
  • View blog
  • Posts: 603
  • Joined: 01-October 08

Re: Return several objects from a function

Posted 26 October 2008 - 07:54 AM

		Dim myStruct As New fooBar
		myStruct = testF("A TEST")




	Public Structure fooBar
		Dim i As Integer
		Dim d As Decimal
		Dim s As String
	End Structure
	Private Function testF(ByVal myFoo As String) As fooBar
		testF.i = 1
		testF.d = 10.1D
		testF.s = myFoo
	End Function
 

Was This Post Helpful? 1
  • +
  • -

#3 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9205
  • View blog
  • Posts: 34,582
  • Joined: 12-June 08

Re: Return several objects from a function

Posted 26 October 2008 - 09:26 AM

Isn't that what datasets are used for? A dataset has a datatable.. a datatable has data columns.. your columns are named for the return values you are getting from the database.. every record's in row format.

Side note, do not do SELECT * from the database.. it's a bad habit to get into, and will one day bite you in the ass (when you return more columns than you are taking care of or less than you were initially).
Was This Post Helpful? 0
  • +
  • -

#4 jens  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 67
  • View blog
  • Posts: 430
  • Joined: 09-May 08

Re: Return several objects from a function

Posted 26 October 2008 - 12:38 PM

dbasnett - thanks!

modi123 - I'll try to keep the "select *"-stuff in mind, thanks. About using datasets or business objects there are different views. What I'm presenting here is a simplification of my real problems. :) A link if you like: http://www.kellerman...essobjects.aspx

/Jens
Was This Post Helpful? 0
  • +
  • -

#5 magicmonkey  Icon User is offline

  • D.I.C Regular

Reputation: 106
  • View blog
  • Posts: 484
  • Joined: 12-September 08

Re: Return several objects from a function

Posted 26 October 2008 - 01:41 PM

I think you are on the right track with your person class, the part you are missing is you want to store each instance of person in a COLLECTION. So as you loop through reading your results from the database you create a new instance of person class set its values then add that class to a collection of person.

There are many benifits to using classes in this fashion, as you can easily add new methods and properties to the class that can be used by your application. As an example add a property FullName that concats the first and last name.

I tried my best to modify your load routine to return a collection instead of your string.

Public Function ListaPersoner(ByVal enamn As String, ByVal e As System.EventArgs) As List(Of personClass)
        Dim MyPersons As New List(Of personClass) 'Collection to store persons in
        Dim newPerson As personClass

        Dim cno As New SqlConnection
        Dim cmd As New SqlCommand
        Dim rdr As SqlDataReader
        Dim command As New SqlCommand

        cno.ConnectionString = connString1
        cmd.Connection = cno
        cmd.Parameters.Add("@Enamn", SqlDbType.NChar, 10)
        cmd.Parameters("@Enamn").Value = enamn

        If enamn.Trim = "" Then
            cmd.CommandText = "SELECT * FROM namn ORDER BY Fnamn"
        Else
            cmd.CommandText = "SELECT * FROM namn where enamn like @Enamn ORDER BY Fnamn"
        End If

        cno.Open()
        rdr = cmd.ExecuteReader
        While rdr.Read
            'Create instance of class, you need to fix class properties with column indexes
            newPerson = New personClass With {._Identitet = rdr.GetInt32(0), ._FörNamn = rdr.GetString(1), ._EfterNamn = rdr.GetString(2), ._Födelse = rdr.GetString(3)}
            'Add new person class to collection
            MyPersons.Add(newPerson)
        End While

        Return MyPersons 'Return Collection
    End Function


This post has been edited by magicmonkey: 26 October 2008 - 01:42 PM

Was This Post Helpful? 1
  • +
  • -

#6 jens  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 67
  • View blog
  • Posts: 430
  • Joined: 09-May 08

Re: Return several objects from a function

Posted 26 October 2008 - 03:32 PM

Great, thank you! I do however feel very curious about how to return an object containing all the objects... Like:

Public Function ListaPersoner(ByVal enamn As String, ByVal e As System.EventArgs) As MultiPersonerClass

How would one go about that? What would the class definition look like?

Public Class MultiPersonerClass
'??????
Dim MultiPersoner as List (of personClass)
'???????
End Class


/Jens
Was This Post Helpful? 0
  • +
  • -

#7 magicmonkey  Icon User is offline

  • D.I.C Regular

Reputation: 106
  • View blog
  • Posts: 484
  • Joined: 12-September 08

Re: Return several objects from a function

Posted 26 October 2008 - 04:18 PM

In my example above I returned it as a generic collection List(of personClass), look at the end of the function to see. This is the easiest way to make a collection, if you wanted to add your own methods properties to the collection then you could inherit the generic collection instead.

Public Class Persons
  Inherits List(Of personClass)

  Public Sub MyOwnMethod()

  End Sub
End Class


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1