CSharpDev
CSharpDev

Reputation: 869

Linq To Sql returns value length instead of value

I just started teaching myself Linq to SQL today. I hardly know anything about linq. That being said, I have a query that i want to return a Name from my database. It is a varchar in the DB

var query = from a in FRESH.Customers
            select a.CUSTOMER_NAME;

dataGridView1.DataSource = query;

This results in a gridview with a column named "Length" and displays the length of every name. If I change the query to select a everything displays fine. What am I doing wrong here?

Upvotes: 2

Views: 1599

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Problem is in gridView, not in Linq - gridView looks for properties of objects in DataSource. And it binds to first found property. Thus it binds strings by Length property (its the only property which String object has).

Default approach for displaying strings in gridView is creating some wrapper, which will have property with string value:

public class StringValue
{    
    public string Value { get; set; }
}

When you create anonymous object, as @DStanley suggested, wrapper is created for you by Linq:

var query = from a in FRESH.Customers
            select new { CustomerName = a.CUSTOMER_NAME};

GridView will look for properties in anonymous object, and it will find and use CustomerName property.

Upvotes: 1

D Stanley
D Stanley

Reputation: 152521

The DataGridView will by default show all of the properties of the type in the list as columns. Since your query is returning a collection of strings and the only1 "property" of a string is Length it shows that as a column.

Try changing to

var query = from a in FRESH.Customers
            select new {Name = a.CUSTOMER_NAME};

1Technically the indexer Chars is a "property" but the DataGridView must be clever enough not to use an indexer as a column.

Upvotes: 5

Related Questions