Search code examples
c#wpfdatagrid

How to get the data out of a DataGrid (C#)


I want to make a vocabulary trainer. For that, I created a class for a Vocabulary. One Vocabulary has three properties (the German word, the other langued word an the status if it's enabled or not). All these properties are in lists

    List<String> germanWords = new List<string>();
    List<String> otherWords = new List<string>();
    List<bool> enabled = new List<bool>();
    List<VocabClass> data = new List<VocabClass>();

All works fine but when I want to change the properties in a DataGrip I can't find a way to get the new data and save it. I tried it with

        data = dataGrip.Items;

But then I get the error CS0029 cannot convert "System.Collections.Generic.List" to "System.Windows.Controls.ItemCollection"


Solution

  • The list stored in Items is a generic list, you would have to convert it to your kind of list. This can be easily done by using LINQ:

    data = dataGrip.Items.Cast<VocabClass>()
                              .Select(item => new VocabClass() { Content = item.Content})
                              .ToList();