Search code examples
c#wpfdatatableobservablecollection

DataTable to observable collection


I have been googling and searching for the answers here, but I still fail to understand a very basic thing - How to convert a DataTable to an ObservableCollection?

This is how far I've gotten:

public ObservableCollection<Test> test;

public class Test
{
    public int id_test { get; set; }
    public string name { get; set; }
} 

Main..

DataTable TestTable = new DataTable();
TestTable.Columns.Add(new DataColumn("id_test", typeof(int)));
TestTable.Columns.Add(new DataColumn("name", typeof(string)));
DS.Tables.Add(TestTable);

var test = new ObservableCollection<Test>();
foreach (DataRow row in test_table.Rows)
{
    var obj = new Test()
    {
        id_test = (int)row.ItemArray[0],
        name = (string)row.ItemArray[1]
    };
    test.Add(obj);
}
        

I updated the code and it seems to be working.


Solution

  • You don't want to create a new collection for each row in the table, but rather one collection for the entire table (with one object in the collection created for one row in the table):

    var test = new ObservableCollection<Test>();
    foreach(var row in TestTable.Rows)
    {
        var obj = new Test()
        {
            id_test = (int)row["id_test"],
            name = (string)row["name"]
        };
        test.Add(obj);
    }