Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Observable Collection?

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.

like image 807
boo_boo_bear Avatar asked May 26 '13 13:05

boo_boo_bear


2 Answers

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);
}
like image 96
Andy Avatar answered Sep 28 '22 06:09

Andy


I had a little issue with the accepted solution. It does not allow the [] brackets on type var.

var test = new ObservableCollection<Test>();
foreach(DataRow row in TestTable.Rows)
{
    test.Add(new Test()
    {
        id_test = (int)row["id_test"],
        name = (string)row["name"],
     });
 }
like image 26
Patrick Cairns Avatar answered Sep 28 '22 08:09

Patrick Cairns