tags:

views:

57

answers:

2
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim ds As DataSet
    ds = getData()
    Dim dt As DataTable = ds.Tables(0)
    Dim gridViewData = From r As DataRow In dt.Rows Select r.Item("foo"), r.Item("bar")
    GridView1.DataSource = gridViewData
    GridView1.DataBind()
End Sub

I just wrote the preceeding code and I get the following compile-time error: "Range variable name can be inferred only from a simple or qualified name with no arguments". Why do I get this error? How can I fix my code?

+1  A: 

Unfortunately, I don't know the VB syntax for this, so I'll just have to show the C# and hope you can work it out:

from DataRow r in dt.Rows
select new 
{
     r.Item("Foo"),
     r.Item("bar")
}

This is saying "Create a new class with two properties", but it has no idea what you want those properties named. If you had done something like this:

from DataRow r in dt.Rows
select new 
{
     r.Count,
     r.NumRows
}

Then it would assume that you wanted the properties called Count and NumRows, but with yours, all it has to go on is Item, which is used by both.

It fix this, you must specify names, explicitly:

from DataRow r in dt.Rows
select new 
{
     Foo = r.Item("Foo"),
     Bar = r.Item("bar")
}
James Curran
+2  A: 

EDIT: Okay, I understand the problem now. It's in the projection. Try this:

Dim gridViewData = From r As DataRow In dt.Rows _
                   Select Foo = r.Item("foo"), Bar = r.Item("bar")

Basically it didn't know what to call the properties in the projection.

Jon Skeet
Thanks, but I get the same error.
Rice Flour Cookies
@Rice Flour Cookies: I've updated my answer, now I think I understand it.
Jon Skeet
@Jon It seems VB.NET requires you to explicity express the property names. I'm curious, would C# infer the property names from the column names so that you didn't have to define them in the projection?
Ben McCormack
@Ben: VB will infer property names if you're using a simple property, I believe... but in this case we're calling an indexer, effectively. C# wouldn't guess it from the arguments either - you'd need something similar. (See James's answer.)
Jon Skeet
@Jon that makes sense. Thanks for the explanation.
Ben McCormack
Thanks, that got rid of the error.
Rice Flour Cookies