DataTable to observable collection

后端 未结 2 1497
清歌不尽
清歌不尽 2020-12-11 05:56

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?

相关标签:
2条回答
  • 2020-12-11 06:35

    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"],
         });
     }
    
    0 讨论(0)
  • 2020-12-11 06:54

    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);
    }
    
    0 讨论(0)
提交回复
热议问题