Fill Grid with single column from linq Query - vb.net

I want to fill by datagrid with information I am getting from a linq query. The datagrid auto generates its columns
Using db As New DataClassesDataContext
Dim fillGrid = From info In db.tableName
Select info.Description
DataGrid1.DataSource = fillGrid
DataGrid1.DataBind()
End Using
This code generates a column called "Length"
If I add another column to select then it generates the columns properly since the list has --> Description = "" : ID = ""
How can I get the linq to generate the column name with a single column?

Linq to sql creates anonymous type when your select is not of a known type. In your case it is a list of string anonymous type. Binding on .net works only for properties and not for fields. So the default property for list of string is Length property which is used to.
Instead of this I would suggest you to create a class with a string property named description and do select as this class object:
Public Class StringCollection
Private _Description As String
Public Property Description() As String
Get
Return _Description
End Get
Set(ByVal value As String)
_Description = value
End Set
End Property
End Class
Then do the selection:
Dim fillGrid = From info In db.tableName
Select New StringCollection With {.Description = info.Pershkrimi}

Related

Retrieve list that is saved in a datatable

I created a datatable containing the list of notes for songs:
Private Table As New DataTable
Public Sub New()
With Table
.Columns.Add("Name")
.Columns.Add("NoteList")
.Rows.Add("GOT", GOT)
.Rows.Add("Yesterday", Yesterday)
End With
End Sub
GOT and Yesterday are lists of notes (notes is a class containing note, duration etc..)
On the form I then assign the datatable to a combobox:
ComboSongs.DisplayMember = Songs.DataTable.Columns(0).ColumnName
ComboSongs.ValueMember = Songs.DataTable.Columns(1).ColumnName
ComboSongs.DataSource = Songs.DataTable
I try to get the list of notes like this:
Dim songToPlay As List(Of Note) = CType(ComboSongs.SelectedValue, List(Of Note))
When I try to get the list I get the error:
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[test.Note]'.'
Now I am unsure where I am getting it wrong. What would be the correct way to do this?
Your ValueMember is what is returned through the ComboBox.SelectedValue. So since you set the ValueMember like this
ComboSongs.ValueMember = Songs.DataTable.Columns(1).ColumnName
you only get the ColumnName. I assume that's a string and, well, the error message tells you it is one
... Unable to cast object of type 'System.String' ...
I guess that should be "NoteList", since that would be returned by Songs.DataTable.Columns(1).ColumnName
But this all doesn't make much sense, as I guess you are selecting a song there, either "Yesterday" or "GOT". At the point you're at it's so convoluted to return the DataTable rows, and index them. You will need to find the row by name and that is just too complicated when you could just create a class with strong names. I'll give you a class based solution but I'm not sure if you can make that change.
Private Class Song
Public Property Name As String
Public Property NoteList As List(Of Note)
End Class
Private Class Note
' your implementation
End Class
Dim songs As New List(Of Song)()
songs.Add(New Song() With {.Name = "GOT", .NoteList = New List(Of Note)})
songs.Add(New Song() With {.Name = "Yesterday", .NoteList = New List(Of Note)})
' need to populate those NoteLists first
ComboSongs.DisplayMember = "Name"
ComboSongs.DataSource = songs
Dim songToPlay = songs.SingleOrDefault(Function(s) s.Name = ComboSongs.SelectedValue)
Dim noteList = songToPlay.NoteList

nhibernate fill class with custom data from different tables

I have a web application (asp.net + SQL db) and I'm mapping it with nHibernate with relative success =).
This web reads an Oracle db (from an ERP system), collects and display data from it but its not using nHibernate for this task.
I have done several reports each one with its own vb.net class that I fill with intrincated queries,
collecting data from a bunch of Oracle tables. So my question is:
Can i do an specific hql query and fill my vb.class in a custom way (Maybe not mapping it), specifying one by one which column of my query fills each property?
===================== EDIT WITH SOLUTION =====================
Just if someone need the resolution, I post the solution in an example.
Public Class classExample
Private pProperty1 As Decimal
Private pProperty2 As String
Public Property Property1() As Decimal
Get
Property1 = pProperty1
End Get
Set(ByVal Value As Decimal)
pProperty1 = Value
End Set
End Property
Public Property Property2() As String
Get
Property2 = pProperty2
End Get
Set(ByVal Value As String)
pProperty2 = Value
End Set
End Property
Public Overloads Function Load() As System.Collections.Generic.List(Of classExample)
Using session As NHibernate.ISession = ISessionFactory.OpenSession()
Dim strsql As String = "SELECT.... FROM...."
Dim Query As NHibernate.IQuery = session.CreateSQLQuery(strsql)
Query.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(Of classExample))
Return Query.List(Of classExample)()
End Using
End Function
End Class
Thanks for your help.
You need to use a result transformer as here (see second code block).

LongListSelector selecteditem

I have a LongListSelector in an .xaml and I am able to fill it by binding to a an ItemSource when the source is filled by a DataContext using a single table from my SQL Server CE database like this:
Dim row = (From rows In db.Hub
Order By rows.HubID Descending
Select rows).ToList()
Me.MainLongListSelector.ItemsSource = row
I am thus able to get the ID of the selected item as follows:
HubID = CType(MainLongListSelector.SelectedItem, Hub).HubID
I am also able to bind to a 'query' DataSource as follows:
Dim row = (From ac In db.Activity
Join at In db.ActivityType On ac.ActivityTypeID Equals at.ActivityTypeID
Select New With {.ID = ac.ActivityID,
.Title = ac.Activity1}).ToList()
Me.MainLongListSelector.ItemsSource = row
however, since this is not referring to a specific table in the DataContext, I cannot get the ID using the above code, ie:
Dim ActID = CType(MainLongListSelector.SelectedItem, Activity).ActivityID '- returns nothing
How should I get the value(s) of selectedItem in this case?
NB: I have created the anonymous fields (.ID and .Title) because those are the names I have bound in the xaml, so the LongListSelected gets populated without writing extra code.
Thanks
Phew!!
I discovered that two things:
this HubID = CType(MainLongListSelector.SelectedItem, Hub).HubID is calling a List (Of DataContext), while in the second scenario above I am using a List (Of Anonymous). So I searched for List (Of Anonymous) and this came up!
I now know I can create a class for List (Of Anonymous) and properly name its properties, thus make it available outside its methods, like in my 'query' question above.
So the answer is I created the class for my anonymous list, declared its properties
Public Class AnonList
Private _id As Integer
Public Property ID() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
Private _title As String
Public Property Title() As String
Get
Return _title
End Get
Set(ByVal value As String)
_title = value
End Set
End Property
Private _desc As String
Public Property Desc() As String
Get
Return _desc
End Get
Set(ByVal value As String)
_desc = value
End Set
End Property
End Class
and therefore assigned them to the ItemSource values,
Select New AnonList With {.ID = ac.ActivityID,
thus being able to get the SelectedItem values as required:
ActivityID = CType(MainLongListSelector.SelectedItem, AnonList).ID
Took a bit of determination to figure that out!

Populate combobox with a class - data from a sql query

Iam frustrated to accomplish a simply population of a combobox, below I have added one new item to the combobox everything seems to be fine.
Question 1 : But how could I get there the information's from the sql query, without having to add it all manually. [ I suppose by simply adding Items.Add line to the while loop ], but here is another thing - The start data is a database record previewer, So it is Simple Name Simple Surname [/] with a dropdown menu with all customers,
Question 2. The data I get from the mysql result is id,name,surname how to point it as the current displayed name/surname and for later purposes - like a update get the selected id of another customer from the dropdown? I don't need the insert command or code just need the information how can I get the id from a selection. If something is unclear don't hesitate to ask.
'Select the first item ( the selection would be a ID of the customer which isn't the index at all)
ComboBoxEdit.SelectedIndex = 0
Form
Dim properties As DevExpress.XtraEditors.Repository.RepositoryItemComboBox = _
ComboBoxEdit.Properties
properties.Items.Add(New Customers(1, "Ta", "t").ToString)
'Select the first item ( the selection would be a ID of the customer which isn't the index at all)
ComboBoxEdit.SelectedIndex = 0
Getting customers into Class Customers ( I guess its that way I need to do it )
Public Function init_customers()
' Create a list of strings.
Dim sql As String
Dim myReader As MySqlDataReader
con.Open()
sql = "select * from customers"
'bind the connection and query
With cmd
.Connection = con
.CommandText = sql
End With
myReader = cmd.ExecuteReader()
While myReader.Read()
list.Add(New Customers(myReader.GetInt64(0), myReader.GetString(1), myReader.GetString(2)))
End While
con.Close()
'Return list
End Function
The class customers
Public Class Customers
Public Sub New(ByVal id As Integer, ByVal name As String, ByVal surname As String)
Me.ID = id
Me.Imie = name
Me.Nazwisko = surname
End Sub
#Region "Get/Set"
Public Property ID() As Integer
Get
Return Me._id
End Get
Set(ByVal value As Integer)
Me._id = value
End Set
End Property
Public Property Imie() As String
Get
Return Me._imie
End Get
Set(ByVal value As String)
Me._imie = value
End Set
End Property
Public Property Nazwisko() As String
Get
Return Me._nazwisko
End Get
Set(ByVal value As String)
Me._nazwisko = value
End Set
End Property
Public ReadOnly Property Surname() As Decimal
Get
Return Me._nazwisko
End Get
End Property
Public Overrides Function ToString() As String
Return _imie + " " + _nazwisko
End Function
#End Region
Private _id As Integer
Private _imie As String
Private _nazwisko As String
End Class
=========== Edit 2 =====================
Ok my dropdown is populated
As I said this is a record preview form so how can I get now the default selection of the combobox.
The thing is I pass there a string
Form1.GridView1.GetRowCellValue(Form1.GridView1.FocusedRowHandle, "Wystawione_na").ToString()
This code returns me SimpleName SimpleSurname - as a one string
Same method is applied to combobox display.
How can I get now the Id of the item, it has to somehow compared and returning a id so it could be set cmbx.SelectedIndex = 0 as the id of customer selection
I take a simpler route, not sure if it's the most efficient though:
Dim Conn As New SqlConnection
Conn.ConnectionString = sYourConnectionString
Conn.Open()
Dim da As New SqlDataAdapter("select * from customers", Conn)
Dim ds As New DataSet
da.Fill(ds, sSql)
cmbxCustomers.DataSource = ds.Tables(0)
cmbxCustomers.ValueMember = "ID" 'or whatever column you want
Of course, I normally use a wrapper class to do almost all of the above code, but the last two lines apply to part of your question.
As far as retrieving that data later based on the ID selected: well you can simply use a DataSet (or DataTable, my preference) class member variable so the data is stored the from the initial load and iterate through the table looking for the row that matches the ID you're wanting information from.

Returning Class Object from Inherited class

I'm trying to teach myself reflection and have been googling but I can't wrap my head around it entirely. I created a class called DataClass which contains a method called GetClassFromDB as you can see below, which will be inherited from multiple classes.
What I am attempting to do is have my dataclass read the TableName property that is defined within objResults. Once I pull in the tablename from objResults I would query the SQL database for a dataset. Once I have the dataset I would create a new object of the same TYPE inheriting this class (Which will be different types) and populate it from the dataset. Once I have the newly populated class I will return it for use.
I believe I have gotten most of the way there properly (Please correct me if there is a better way), but my real question is this. How can I create a new class of the type thats deriving that class from that string name that I getting in my code, or the type. I would want to have all the accessible properties from objResults available.
Namespace MyApp
Public Class DataClass
Private _TableName As String
Private _Name As String
Overridable ReadOnly Property TableName As String
Get
Return _TableName
End Get
End Property
Public Overloads Function GetClassFromDB() As Object
Try
Dim BaseObject As New Object
'Get the object name
Dim objName As String = MyBase.GetType().Name
'Gets the type thats calling this method
Dim objDerived As Type = MyBase.GetType()
'Get the property info to request the tablename from the derived class
Dim TableName As PropertyInfo = objDerived.GetProperty("TableName")
Dim TableNameString As String = TableName.GetValue(Me, Nothing).ToString
'Once I get the table name from objResults I can perform the SQL
Dim QueryResults as DataSet = SQLiteCLass.Query("Select * FROM TableNameString")
'Once I get data from the SQL I want to create a new object of the type deriving this method.
'In this example is objResults
Dim NewObject as objDerived
'Now I can fill my new object with the results and return it as an object
'THIS IS MY QUESTION - How can I create a new object of the TYPE that I receive from Reflection
Return False
Catch ex As Exception
Return False
End Try
End Function
End Class
End Namespace
and this is a sample class that would inherit my dataclass.
Public Class objResults
Inherits MyApp.DataClass
Private _GameID As Guid
Public Property GameID As Guid
Get
Return _GameID
End Get
Set(ByVal value As Guid)
_GameID = value
End Set
End Property
Public Overrides ReadOnly Property TableName As String
Get
Return "This is my tablename"
End Get
End Property
End Class
and this is how I would use this in code.
Dim objResult as New objResults
Dim TodaysResult as objResultsCollection
TodaysResult = objResult.GetClassFromDB()