Binding VB.net DataRepeater to dataview items at runtime with aggregation using linq - vb.net

Hoping someone can help me out with what is probably a dumb question.
I'm trying to use a datarepeater to display data generated via LINQ from a datatable
I've managed to do this fine with a filtered existing datasource using:
Me.Tbl_52TableAdapter.Fill(Me.CBRDataSet.tbl_52)
Dim query =
From dlist In CBRDataSet.tbl_52.AsEnumerable
Where (dlist.Field(Of String)("TL") = "CTS 06")
Select dlist
query.CopyToDataTable().AsDataView()
DataRepeater1.DataSource = query
The problem being that I need to aggregate a field in the dataset into a count.
If I replace the query with:
Dim query =
From CountAgent In CBRDataSet.tbl_52.AsEnumerable
Group CountAgent By PBX = CountAgent.Field(Of String)("TL") Into Count()
Select Count
It then states that:
'CopyToDataTable' is not a member of 'System.Collections.Generic.IEnumerable(Of Integer)'
I've tried to get around it by changing the declaration to:
Dim query As IEnumerable(Of DataRow) =
Which compiles, but I have no idea if it works, and I cant check as I can't find a way to bind a label to the produced count col of the dataview.
If anyone can tell me what I'm doing wrong i'd be most appreciative.

Coming back to my own question, in case it helps anyone else: MSDN had the answer -
You need to overload copyToDataTable as described in
"How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow"
on:
http://msdn.microsoft.com/en-us/library/bb669096.aspx

Related

visual basic find database total

I'm working on creating a visual basic program that can find the sum total of a column from a database file and display it in a label control, and have been stuck for a while. I was hoping that someone could help me out a little.
I've tried a few different ways to accomplish it and they each keep throwing out the same error.
Dim SumQuery = From popualtion In PopulationDBDataSet.City
Aggregate order In PopulationDBDataSet.City
Into Sum(PopulationDBDataSet.City.PopulationColumn)
lblTotalPop.Text = SumQuery.ToString
and
Dim SumQuery = Aggregate Populaton In PopulationDBDataSet.City
Into Sumorders = Sum(PopulationDBDataSet.City.PopulationColumn)
lblAvgPop.Text = SumQuery.ToString
Both attempts produce the error "method sum not accessible in this context". Sorry for this post being a bit long but I'm out of ideas on this.
Your usage should include the variable used in Aggregate function:
Try this:
Dim SumQuery = From popualtion In PopulationDBDataSet.City
Aggregate order In PopulationDBDataSet.City
Into Sum(order.PopulationColumn)

Range variable name cannot match the name of a member of the 'Object' class. when querying a DataGridView using Linq

I am trying to Query a DataGridViewRowsCollection object using LINQ so I don't need a for loop. I want to get the first cells out what is a String and put it in a generic list.
Based on my knowledge and research the query should be the following:
Dim Result As List(Of String) = (From row In gridMappingClasses.Rows.Cast(Of DataGridViewRow)()
Select row.Cells(0).Value.ToString).ToList()
but it fails with the following error: Range variable name cannot match the name of a member of the 'Object' class.
But if I remove the ToString method call and change Result to List(of object) it works fine. Btw I am using Strict on.
Can anyone help?
Try giving it an alias (ToString is already a member of Object, can't have another one):
(From row In gridMappingClasses.Rows.Cast(Of DataGridViewRow)()
Select v = row.Cells(0).Value.ToString).toList
But there is nothing wrong with having a for loop. You should generally use LINQ for simple queries that don't cause any debugging headache. If a LINQ query starts to become problematic, it's time to rewrite it as a loop. In your case it would have resolved the problem.

Autocomplete list does not show all possible completions with BindingSource.Item

I've got a BindingSource for a DataSet. I'm fairly new to this whole binding business and databases, and it took me hours to figure out how to use BindingSource to get to an item, because the Row method was not included in the autocomplete. Not to confuse anyone, here's some sample code:
Dim somePreperty As String
Dim dataSet As New MyDataSet
Dim table As New MyDataSetTableAdapters.MyTableAdapter
Dim source As New BindingSource
source.DataSource = dataSet
source.DataMember = "SomeMember"
table.Fill(dataSet.SomeMember)
lablCabinet.DataBindings.Add("Text", source(0), "MemberID") '<This works fine>'
someProperty = source.Item(0).Row("ProductModel") '<So does this>'
The code runs perfectly and does exactly what I want. My problem is the following: When I've typed in source.Item(0)., autocomplete does not display Row in the list. Is this perhaps not the best way to do what I'm doing? Is there a reason it's hidden? Is this a good coding practice to do so? The fact that is wasn't there took me lots of time Googling, so I'm trying to figure out whether it's a Visual Studio glitch or my own.
Thanks in advance! = )
source.item(0) returns an object, so intellisense has no idea what is is.
You know what it should be, the compiler does not.
If you cast it first to a table or assing it to a table, intellisense will kick in.
So either:
ctype(source.item(0),datatable)
Or
dim tbl as datatable=source.item(0).

Linq to Datarow, Select multiple columns as distinct?

basically i'm trying to reproduce the following mssql query as LINQ
SELECT DISTINCT [TABLENAME], [COLUMNNAME] FROM [DATATABLE]
the closest i've got is
Dim query = (From row As DataRow In ds.Tables("DATATABLE").Rows _
Select row("COLUMNNAME") ,row("TABLENAME").Distinct
when i do the above i get the error
Range variable name can be inferred
only from a simple or qualified name
with no arguments.
i was sort of expecting it to return a collection that i could then iterate through and perform actions for each entry.
maybe a datarow collection?
As a complete LINQ newb, i'm not sure what i'm missing.
i've tried variations on
Select new with { row("COLUMNNAME") ,row("TABLENAME")}
and get:
Anonymous type member name can be
inferred only from a simple or
qualified name with no arguments.
to get around this i've tried
Dim query = From r In ds.Tables("DATATABLE").AsEnumerable _
Select New String(1) {r("TABLENAME"), r("COLUMNNAME")} Distinct
however it doesn't seem to be doing the distinct thing properly.
Also, does anyone know of any good books/resources to get fluent?
You start using LINQ on your datatable objects, you run the query against dt.AsEnumberable, which returns an IEnumerable collection of DataRow objects.
Dim query = From row As DataRow In ds.Tables("DATATABLE").AsEnumerable _
Select row("COLUMNNAME") ,row("TABLENAME")
You might want to say row("COLUMNNAME").ToString(), etc. Query will end up being an IEnumerable of an anonymous type with 2 string properties; is that what you're after? You might need to specify the names of the properties; I don't think the compiler will infer them.
Dim query = From row As DataRow In ds.Tables("DATATABLE").AsEnumerable _
Select .ColumnName = row("COLUMNNAME"), .TableName = row("TABLENAME")
This assumes that in your original sql query, for which you used ADO to get this dataset, you made sure your results were distinct.
Common cause of confusion:
One key is that Linq-to-SQL and (the Linq-to-object activity commonly called) LINQ-to-Dataset are two very different things. In both you'll see LINQ being used, so it often causes confusion.
LINQ-to-Dataset
is:
1 getting your datatable the same old way you always have, with data adapters and connections etc., ending up with the traditional datatable object. And then instead of iterating through the rows as you did before, you're:
2 running linq queries against dt.AsEnumerable, which is an IEnumerable of datarow objects.
Linq-to-dataset is choosing to (A) NOT use Linq-to-SQL but instead use traditional ADO.NET, but then (B) once you have your datatable, using LINQ(-to-object) to retrieve/arrange/filter the data in your datatables, rather than how we've been doing it for 6 years. I do this a lot. I love my regular ado sql (with the tools I've developed), but LINQ is great
LINQ-to-SQL
is a different beast, with vastly different things happening under the hood. In LINQ-To-SQL, you:
1 define a schema that matches your db, using the tools in in Visual Studio, which gives you simple entity objects matching your schema.
2 You write linq queries using the db Context, and get these entities returned as results.
Under the hood, at runtime .NET translates these LINQ queries to SQL and sends them to the DB, and then translates the data return to your entity objects that you defined in your schema.
Other resources:
Well, that's quite a truncated summary. To further understand these two very separate things, check out:
LINQ-to-SQL
LINQ-to-Dataset
A fantastic book on LINQ is LINQ in Action, my Fabrice Marguerie, Steve Eichert and Jim Wooley (Manning). Go get it! Just what you're after. Very good. LINQ is not a flash in the pan, and worth getting a book about. In .NET there's way to much to learn, but time spent mastering LINQ is time well spent.
I think i've figured it out.
Thanks for your help.
Maybe there's an easier way though?
What i've done is
Dim comp As StringArrayComparer = New StringArrayComparer
Dim query = (From r In ds.Tables("DATATABLE").AsEnumerable _
Select New String(1) {r("TABLENAME"), r("COLUMNNAME")}).Distinct(comp)
this returns a new string array (2 elements) running a custom comparer
Public Class StringArrayComparer
Implements IEqualityComparer(Of String())
Public Shadows Function Equals(ByVal x() As String, ByVal y() As String) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of String()).Equals
Dim retVal As Boolean = True
For i As Integer = 0 To x.Length - 1
If x(i) = y(i) And retVal Then
retVal = True
Else
retVal = False
End If
Next
Return retVal
End Function
Public Shadows Function GetHashCode(ByVal obj() As String) As Integer Implements System.Collections.Generic.IEqualityComparer(Of String()).GetHashCode
End Function
End Class
Check out the linq to sql samples:
http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx
Pretty useful to learn SQL. And if you want to practice then use LinqPad
HTH
I had the same question and from various bits I'm learning about LINQ and IEnumerables, the following worked for me:
Dim query = (From row As DataRow In ds.Tables("DATATABLE").Rows _
Select row!COLUMNNAME, row!TABLENAME).Distinct
Strangely using the old VB bang (!) syntax got rid of the "Range variable name..." error BUT the key difference is using the .Distinct method on the query result (IEnumerable) object rather than trying to use the Distinct keyword within the query.
This LINQ query then returns an IEnumerable collection of anonymous type with properties matching the selected columns from the DataRow, so the following code is then accessible:
For Each result In query
Msgbox(result.TABLENAME & "." & result.COLUMNNAME)
Next
Hoping this helps somebody else stumbling across this question...

ComboBox DataBinding DisplayMember and LINQ queries

Update
I decided to iterate through the Data.DataTable and trimmed the values there.
Utilizing SirDemon's post, I have updated the code a little bit:
Sub test(ByVal path As String)
Dim oData As GSDataObject = GetDataObj(path)
EmptyComboBoxes()
Dim oDT As New Data.DataTable
Try
Dim t = From r In oData.GetTable(String.Format("SELECT * FROM {0}gsobj\paths ORDER BY keyid", AddBS(path))) Select r
If t.Count > 0 Then
oDT = t.CopyToDataTable
For Each dr As Data.DataRow In oDT.Rows
dr.Item("key_code") = dr.Item("key_code").ToString.Trim
dr.Item("descript") = dr.Item("descript").ToString.Trim
Next
dataPathComboBox.DataSource = oDT
dataPathComboBox.DisplayMember = "descript"
dataPathComboBox.ValueMember = "key_code"
dataPathComboBox.SelectedIndex = 0
dataPathComboBox.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
This works almost as I need it to, the data is originally from a foxpro table, so the strings it returns are <value> plus (<Field>.maxlength-<value>.length) of trailing whitespace characters. For example, a field with a 12 character length has a value of bob. When I query the database, I get "bob_________", where _ is a space.
I have tried a couple of different things to get rid of the whitespace such as:
dataPathComboBox.DisplayMember.Trim()
dataPathComboBox.DisplayMember = "descript".Trim.
But nothing has worked yet. Other than iterating through the Data.DataTable or creating a custom CopyToDataTable method, is there any way I can trim the values? Perhaps it can be done in-line with the LINQ query?
Here is the code I have so far, I have no problem querying the database and getting the information, but I cannot figure out how to display the proper text in the ComboBox list. I always get System.Data.DataRow :
Try
Dim t = From r In oData.GetTable("SELECT * FROM ../gsobj/paths ORDER BY keyid") _
Select r
dataPathComboBox.DataSource = t.ToList
dataPathComboBox.SelectedIndex = 0
'dataPathComboBox.DisplayMember = t.ToList.First.Item("descript")
dataPathComboBox.Enabled = True
Catch ex As Exception
Stop
End Try
I know that on the DisplayMember line the .First.Item() part is wrong, I just wanted to show what row I am trying to designate as the DisplayMember.
I'm pretty sure your code tries to set an entire DataRow to a property that is simply the name of the Field (in a strongly type class) or a Column (in a DataTable).
dataPathComboBox.DisplayMember = "descript"
Should work if the DataTable contains a retrieved column of that name.
Also, I'd suggest setting your SelectedIndex only AFTER you've done the DataBinding and you know you actually have items, otherwise SelectedIndex = 0 may throw an exception.
EDIT: Trimming the name of the bound column will trim just that, not the actual bound value string. You either have to go through all the items after they've been bound and do something like:
dataPathComboBox.Item[i].Text = dataPathComboBox.Item[i].Text.Trim()
For each one of the items. Not sure what ComboBox control you're using, so the item collection name might be something else.
Another solution is doing that for each item when it is bound if the ComboBox control exposes an onItemDataBound event of some kind.
There are plenty of other ways to do this, depending on what the control itself offers and what you choose to do.
DisplayMember is intended to indicate the name of the property holding the value to be displayed.
In your case, I'm not sure what the syntax will by since you seem to be using a DataSet, but that should be
... DisplayMember="Item['descript']" ...
in Xaml, unless you need to switch that at runtime in which case you can do it in code with
dataPathComboBox.DisplayMember = "Item['descript']"
Again, not 100% sure on the syntax. If you are using a strongly typed DataSet it's even easier since you should have a "descript" property on your row, but given hat your error indicates "System.DataRow" and not a custom type, I guess you are not.
Because I can't figure out the underlying type of the datasource you are using I suggest you to change commented string to
dataPathComboBox.DisplayMember = t.ElementType.GetProperties.GetValue(0).Name
and try to determine correct index (initially it is zero) in practice.