I've got a simple WPFToolkit DataGrid
:
<Grid>
<dg:DataGrid Name="theDataGrid"/>
</Grid>
And in code behind a simple Contact
class:
public class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Contact(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}
In my main constructor in code behind, I build a List
collection and bind it to my DataGrid
:
List<Contact> contacts = new List<Contact>();
contacts.Add(new Contact("John", "Tester"));
contacts.Add(new Contact("Jill", "Tester"));
contacts.Add(new Contact("Joe", "Tester"));
contacts.Add(new Contact("Jimmy", "Nontester"));
theDataGrid.ItemsSource = contacts;
and that works fine, but if I filter these contacts with LINQ like this:
List<Contact> contacts = new List<Contact>();
contacts.Add(new Contact("John", "Tester"));
contacts.Add(new Contact("Jill", "Tester"));
contacts.Add(new Contact("Joe", "Tester"));
contacts.Add(new Contact("Jimmy", "Nontester"));
var filteredContacts = contacts.Where(contact => contact.LastName.StartsWith("T"));
theDataGrid.ItemsSource = filteredContacts;
Then my DataGrid
is populated, but the fields are all empty (!). For example, in the above case, my DataGrid
has three rows which are all empty. Strangely when debugging, filteredContacts
contains four items.
How can I use LINQ to filter my custom objects AND get them to display in my DataGrid
?
Best Solution
i would try two things :
Change
to
The second would be to use a View and filter on the View.