I’m building a MVC structure for a part of my program.
I’ve done the Models of 5-10 tables and what they have in common is only the constructor. (which takes the recordset.fields)
Here’s my function to fill these objects:
Public Function reqTable(ByVal pTable As String, ByVal pType As Type, ByVal pNoProjet As Integer, Optional ByVal strAdditionnalConditions As String = "") As List(Of Object)
Dim lstRetour As List(Of Object) = New List(Of Object)
rsRequestCSV = conSQL.Execute("SELECT * FROM " & pTable & " WHERE NoProjet = " & pNoProjet & " " & strAdditionnalConditions)
With rsRequestCSV
While Not .EOF
lstRetour.Add(Activator.CreateInstance(pType, New Object() {rsRequestCSV.Fields})) 'New clsTable(rsRequestCSV.Fields))
.MoveNext()
End While
End With
Return lstRetour
End Function
What I’m not able to achieve is to return a List(Of pType) instead of List(Of Object).
The reason I want this is to have headers in my datagridviews even if they’re empty.
So is there a way to return a List(Of MyModel’sType) ?
thanks in advance!
Just use
As pTypeinstead ofAs Object(but consider using a conventional type argument name, i.e.Tinstead ofpType), remove the now obsoletepTypeargument, and use the following to create and add the instances:GetTpe(T)gets you aSystem.Typeinstance representing the type argument. Since VB, unlike Java, has reified generic types you can thus create instances from type argument.Apart from that, pay attention that .NET has different code style conventions than Java; for instance, all methods should use PascalCase, not camelCase. And like in Java, use of Hungarian notation is discouraged. Use concise but descriptive names. And, as Rene noted, your code suffers from an SQL injection vulnerability.