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.
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);
}
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"],
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With