DataTable for observable collection

I've searched for answers and searched for answers here, but I still don't understand a very simple thing. How do I convert a DataTable to an observable collection?

This is how far I got:

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 have updated the code and it seems to work.

+2


source to share


2 answers


You don't want to create a new collection for every row of 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);
}

      

+3


source


I had a little problem with the accepted solution. It does not allow brackets [] on 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"],
     });
 }

      

0


source







All Articles