Reputation: 3770
I am simply trying to create an function to return a set of user. But, in order to be able to add the item later to a collection I used arrayList, but at last I am getting an error of Type ArrayList cannot be converted to 1-Dimensional array of Users
Here is my Code:
Function getDoctorsList() As Users()
Dim userCollection As New ArrayList
Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
Dim dr As SqlDataReader = dbHelper.ExecuteAndGetReader(sql)
While dr.Read
Dim user As New Users
user.Id = IIf(IsDBNull(dr("id")), 0, dr("id"))
user.UserName = IIf(IsDBNull(dr("username")), "", dr("username"))
user.UserNin = IIf(IsDBNull(dr("user_nin")), 0, dr("user_nin"))
user.UserType = IIf(IsDBNull(dr("usertype")), "", dr("usertype"))
user.Password = IIf(IsDBNull(dr("password")), "", dr("password"))
userCollection.Add(user)
End While
Return userCollection
End Function
How to solve such problems?
Upvotes: 0
Views: 126
Reputation: 101112
Either let your method return an ArrayList
:
Function getDoctorsList() As ArrayList()
create an Array
out of your ArrayList
:
Return userCollection.ToArray()
or, the best solution, let your method return an IEnumerable(Of User)
Function getDoctorsList() As IEnumerable(Of User)
you should also use a List(of User)
instead of a ArrayList
instead, since it is type safe (and clearer) and it also implements IEnumerable(Of User)
.
Edit
Example using IEnumerable(of Users)
and DataRowExtensions
:
Function GetDoctorsList() As IEnumerable(of Users)
Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
Dim table = new DataTable()
table.Load(dbHelper.ExecuteAndGetReader(sql))
Return (from row in table.AsEnumerable()
select new User() With
{
.Id = row.FieldOf(Of Integer)("id"),
.UserName = row.Field(Of String)("username"),
.UserNin = row.Field(Of Integer)("user_nin"),
.UserType = row.Field(Of String)("usertype"),
.Password = row.Field(Of String)("password")
}).ToList()
End Function
Upvotes: 1