DataTable 到 observable 集合 [英] DataTable to observable collection
本文介绍了DataTable 到 observable 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在谷歌上搜索并在这里寻找答案,但我仍然无法理解一个非常基本的东西 - 如何将 DataTable 转换为 Observable 集合?
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?
这是我得到的程度:
public ObservableCollection<Test> test;
public class Test
{
public int id_test { get; set; }
public string name { get; set; }
}
主要...
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.
推荐答案
您不想为表中的每一行创建一个新集合,而是为整个表创建一个集合(在创建的集合中创建一个对象)表中的一行):
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);
}
这篇关于DataTable 到 observable 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文