Populate dropdown box from SQL Server using a function - vb.net

I am trying to follow this video that is written in C# and convert it to vb (to Populate a dropdown box from SQL Server using a function)
here is the working C# code:
private list<product> getallprodcuts()
{
Try
{
using(PropSolWebDBEntities db= new PropSolWebDBEntities())
list<product> products = (from x in db.product select x).tolist;
}
catch(exception)
{
Return Null;
}
}
And the vb that I cant get to work:
Private Function getallproducts() As List( Of<product>)
Try
Dim db As New PropSolWebDBEntities
Dim products As list <product> = (from x in db.product select x).tolist
Return products
Catch ex As Exception
Return vbNull
End Try
End Function
What am I doing wrong?

List should be translated as List(of product).
return null should be translated as Return Nothing.
Use using instead of declaring the db variable.
I don't compile the code, but it's like this:
Private Function getallproducts() As List(Of product)
Try
Using db As New PropSolWebDBEntities
Dim products As list(Of product) = (From x In db.product Select x).ToList()
Return products
End Using
Catch ex As Exception
Return Nothing
End Try
End Function

You don't need the LINQ part since you are not filtering/grouping/ordering by. The Using block takes care of your context disposal for you. You just missed some syntax difference.
Private Function getallproducts() As List(Of product)
Dim results As List(Of product) = Nothing
Using db As New PropSolWebDBEntities
results = db.product.ToList
End Using
Return results
End Function

Related

Convert Database Linq Query Results to String List

I am trying to use a LINQ query to grab some data from a database, and since I am grabbing just one column of data I want to store it within a string list. This is the code I have.
Dim POList As New List(Of String)
Using dbContext As New DBLINQDataContext
Dim query = (From o In dbContext.Orders
Where o.Order_Number.StartsWith(JobNumber)
Select o.Order_Number)
POList = query.ToList()
End Using
MessageBox.Show(POList.ToString())
When I run this the data in the MessageBox is
System.Collections.Generic.List`1[System.String]
There is no table data, even though I know there are actual data points for me to be getting :\
POList.ToString() will display the name of the object type.
You can use string.Join(",", POList.ToString()).
You can also define an extension method StringJoin() to show your list as string if you are going to use it frequently.
Here is an extension method that you can use:
public static StringExtensions
{
public static string StringJoin(this IEnumerable<string> strings, string seperator)
{
if (strings == null) return null;
return string.Join(seperator, strings);
}
}
Since this was a vb.net question, I translated #vendettamit 's excellent answer for the benifit of future vb readers.
Public Module StringExtensions
<Extension()>
Public Function StringJoin(MyStrings As IEnumerable(Of String), separator As String) As String
If MyStrings Is Nothing Then
Return Nothing
Else
Return String.Join(separator, MyStrings)
End If
End Function
End Module
To use the extension...
Dim l As New List(Of String) From {"Mathew", "Mark", "Luke", "John"}
Dim s As String = l.StringJoin(", ")
Debug.Print(s)

InvalidCastException when trying to Sum datatable rows with LINQ

Hi i am trying to sum all my datatable values to one row. but i retrieve a InvalidCastException:
Failed to convert an object of
typeWhereSelectEnumerableIterator2[System.Linq.IGrouping2[System.Object,System.Data.DataRow],VB$AnonymousType_0`4[System.Object,System.Double,System.Decimal,System.Decimal]]
to type System.Data.DataTable.
SQL Datatypes:
NAME_AGE string
LON money
sal_tjformon money
sal_sjuklon money
Private Function GroupByName(dataTable As DataTable) As DataTable
Dim result = dataTable.AsEnumerable().GroupBy(
Function(row) row.Item("NAME_AGE")).Select(Function(group) New With {
.Grp = group.Key,
.LON = group.Sum(Function(r) Decimal.Parse(r.Item("LON"))),
.sal_tjformon = group.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon"))),
.sal_sjuklon = group.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon")))
})
Return result
The LINQ statement returns an IEnumerable(Of <anonymous_type>). There are two problems with this. First of all, your function returns a DataTable, which your object definitely is not. Secondly of all, you can't return an anonymous type from a function call.
If you want to return the select result, you have to create an explicit type (a class) and return the IEnumerable(Of MyType), like in the code below. I strongly advice to set an explicit type to the Grp property (like String?).
Class GroupNameAgeResult
Public Property Grp As Object
Public Property LON As Decimal
Public Property sal_tjformon As Decimal
Public Property sal_sjuklon As Decimal
End Class
Private Function GroupByName(dataTable As DataTable) As IEnumerable(Of GroupNameAgeResult)
Dim result = dataTable.AsEnumerable().GroupBy(Function(row) row.Item("NAME_AGE")) _
.Select(Function(grp) New GroupNameAgeResult() With
{.Grp = grp.Key,
.LON = grp.Sum(Function(r) Decimal.Parse(r.Item("LON").ToString)),
.sal_tjformon = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon").ToString)),
.sal_sjuklon = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon").ToString))})
Return result
End Function
If you want to return a DataTable, you can define this, loop over the groups and add a row. You can return afterwards the result. See example code below.
Private Function GroupByName(dataTable As DataTable) As DataTable
Dim result As New DataTable()
result.Columns.Add("Grp", GetType(Object))
result.Columns.Add("LON", GetType(Decimal))
result.Columns.Add("sal_tjformon", GetType(Decimal))
result.Columns.Add("sal_sjuklon", GetType(Decimal))
For Each grp In dataTable.AsEnumerable().GroupBy(Function(row) row.Item("NAME_AGE"))
Dim row As DataRow = result.NewRow()
row.Item("Grp") = grp.Key
row.Item("LON") = grp.Sum(Function(r) Decimal.Parse(r.Item("LON").ToString))
row.Item("sal_tjformon") = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon").ToString))
row.Item("sal_sjuklon") = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon").ToString))
result.Rows.Add(row)
Next
Return result
End Function
Last but not least. I strongly advice you to turn on "Option strict" (you can set this in the project properties -> Compile). You'll notice many more (possible) errors with your code (even the small function from this question).

Linq Statement In vb

I am new to vb well not new but used chsarp for years I cant figure out what's wrong with this statement. The debugger is not even hitting the return list part so I don't no what is up. I am using the same context to add files so i don't think its the way i declared it
Private threeSoftwareContext As New R3DeliveryEntities1
Public Function GetAlLFilesToBeProcessedByLocation(location As Int32, status As StatusTypes) As List(Of downloadedFile)
Dim list As New List(Of downloadedFile)
list = (From files In threeSoftwareContext.downloadedFiles Where files.location = 0 And files.status = status).ToList()
Return list
End Function
Exception message
i got it working with this but what i dont no in vb is how do I give it columns names
Dim retVal As List(Of downloadedFile)
Try
retVal = (From files In threeSoftwareContext.downloadedFiles Where files.location = 0).ToList()
Return retVal
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Return retVal

Linq return result as list

Hi I am stuck with return the linq result as list. I try to convert but failed to return as the list. Below is my code. Please help. Thanks
Public Function GetConfigList(ByVal aConfig As TT_GENERAL_CONFIGURATION) As List(Of Config)
Dim Data = From p In Db.TT_GENERAL_CONFIGURATION _
Select p
If Data IsNot Nothing Then
ConvertGeneralConfig(Data)
Else
Return Nothing
End If
End Function
Private Function ConvertGeneralConfig(ByVal aConfig As TT_GENERAL_CONFIGURATION) As List(Of Config)
Dim pConfig As New Config
pConfig.ConfigID = aConfig.INTERNAL_NUM
pConfig.ConfigType = aConfig.CONFIG_TYPE
pConfig.ConfigName = aConfig.CONFIG_NAME
pConfig.ConfigValue = aConfig.CONFIG_VALUE
Return pConfig
End Function
Seems like you might want to use
If Data IsNot Nothing Then
Return ConvertGeneralConfig(Data)
Else
Return Nothing
End If
If you only expect one result - then use First() or a FirstOrDefault()
Dim Data = (From p In Db.TT_GENERAL_CONFIGURATION _
Select p)
.FirstOrDefault();
your Data now only contains the first element of the result. If none was found Data is nothing.
UPDATE
If you want your function to return a list then you have to create a list, and return it:
Private Function ConvertGeneralConfig(ByVal aConfig As TT_GENERAL_CONFIGURATION) As List(Of Config)
Dim pConfig As New Config
pConfig.ConfigID = aConfig.INTERNAL_NUM
pConfig.ConfigType = aConfig.CONFIG_TYPE
pConfig.ConfigName = aConfig.CONFIG_NAME
pConfig.ConfigValue = aConfig.CONFIG_VALUE
Dim lst As New List(Of Config) 'Creates a list
lst.Add(pConfig) ' add the object to the list
Return lst ' returns the list
End Function

Function to populate list not working

I am trying to get the following to work
Function AddService(id As Integer) As ViewResult
Dim serv As RequestedService = New RequestedService
serv.JobId = id
Dim ServiceList = New List(Of RequestedService)()
Dim ServiceQuery = From s In db.Services
Select s
ServiceList.AddRange(ServiceQuery)
ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)
Return View(serv)
End Function
But
ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)
Gives me the following error: 's' is not declared. It may be inaccessible due to its protection level.
I cannot work out how to correct this. Essentially I need to populate the SelectList with both an id and string and pass it to the view?
Assuming that the RequestedService model has properties called IDServices and ServiceName you could use the following:
ViewBag.ServiceId = New SelectList(ServiceList, "IDServices", "ServiceName")
But you really don't need this intermediary list:
Function AddService(id As Integer) As ViewResult
Dim serv As RequestedService = New RequestedService
serv.JobId = id
ViewBag.ServiceId = New SelectList(db.Services, "IDServices", "ServiceName")
Return View(serv)
End Function
And you really, really, really don't need to use ViewBag, but use view models instead.
Function AddService(id As Integer) As ViewResult
Dim model = New RequestedServiceViewModel
model.JobId = id
model.Services = New SelectList(db.Services, "IDServices", "ServiceName")
Return View(model)
End Function
and now your view is strongly typed to the view model:
#ModelType RequestedServiceViewModel
#Html.DropDownListFor(Function(x) x.ServiceId, Model.Services)