I have a List<Indicators>
where Indicators has several properties.
I have a ListView which holds selected properties of that class as a list of strings.
I want to create a DataTable from the List using only the selected properties in the listview.
So far I can create the columns for the DataTable with the selected parameters in listview. I'm stuck on how to fill each row with data from selected columns only.
the for
block is where I'm stuck, I know what I have there isn't right. Any help is appreciated, thanks.
internal DataTable ConvertToDataTableAll(List<Indicators> data)
{
DataTable table = new DataTable();
foreach (ListViewItem item in listviewFeatures.Items)
{
table.Columns.Add(item.Text);
//this for block should fill the current column with data.
for (int i = 0; i < data.Count; i++)
{
var row = table.NewRow();
table.Rows.InsertAt(row, i);
table.Rows[i][item.Text] = data.Select(x => item.Text);
}
}
}
Solution with some changes to CodingYoshis suggestion. This is after adding all columns from code above and removing the for block.
foreach(Indicators ind in data)
{
var row = table.NewRow();
foreach(PropertyInfo prop in ind.GetType().GetProperties())
{
if (table.Columns.Contains(prop.Name))
{
row[prop.Name] = prop.GetValue(ind);
}
}
table.Rows.Add(row);
}