C# DataTable 到 observable 集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16759603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataTable to observable collection
提问by boo_boo_bear
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.
我更新了代码,它似乎有效。
采纳答案by Andy
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);
}
回答by Patrick Cairns
I had a little issue with the accepted solution. It does not allow the [] brackets on type var.
我对接受的解决方案有一点问题。它不允许在类型 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"],
});
}

