observablecollection 到 dataView 或数据集
observablecollection to dataView or dataset
我有一个通过绑定 observablecollection 形成的数据网格,现在我想提供导出到 excel 函数,所以我需要通过数据网格转换为数据集或数据视图。
public ObservableCollection<DataSourceVM> Backends { get; set; }
private void StartExport(String filepath)
{
try
{
DataTable bs = _dataGrid.ItemsSource as DataTable;
_dataSet = bs.DataSet as DataSet;
}
catch (Exception e1)
{
MessageBox.Show("error");
}
}
ItemSource 包含基础class 和后端实体class
您需要使用所需的列手动创建数据表。我假设这些列是 DataSourceVM class.
的属性
public ObservableCollection<DataSourceVM> Backends { get; set; }
private void StartExport(String filepath)
{
try
{
var dataSet = new DataSet();
var dataTable = new DataTable();
dataSet.Tables.Add(dataTable);
// we assume that the properties of DataSourceVM are the columns of the table
// you can also provide the type via the second parameter
dataTable.Columns.Add("Property1");
dataTable.Columns.Add("Property2");
foreach (var element in Backends)
{
var newRow = dataTable.NewRow();
// fill the properties into the cells
newRow["Property1"] = element.Property1;
newRow["Property2"] = element.Property2;
dataTable.Rows.Add(newRow);
}
// Do excel export
}
catch (Exception e1)
{
MessageBox.Show("error");
}
}
我有一个通过绑定 observablecollection 形成的数据网格,现在我想提供导出到 excel 函数,所以我需要通过数据网格转换为数据集或数据视图。
public ObservableCollection<DataSourceVM> Backends { get; set; }
private void StartExport(String filepath)
{
try
{
DataTable bs = _dataGrid.ItemsSource as DataTable;
_dataSet = bs.DataSet as DataSet;
}
catch (Exception e1)
{
MessageBox.Show("error");
}
}
ItemSource 包含基础class 和后端实体class
您需要使用所需的列手动创建数据表。我假设这些列是 DataSourceVM class.
的属性public ObservableCollection<DataSourceVM> Backends { get; set; }
private void StartExport(String filepath)
{
try
{
var dataSet = new DataSet();
var dataTable = new DataTable();
dataSet.Tables.Add(dataTable);
// we assume that the properties of DataSourceVM are the columns of the table
// you can also provide the type via the second parameter
dataTable.Columns.Add("Property1");
dataTable.Columns.Add("Property2");
foreach (var element in Backends)
{
var newRow = dataTable.NewRow();
// fill the properties into the cells
newRow["Property1"] = element.Property1;
newRow["Property2"] = element.Property2;
dataTable.Rows.Add(newRow);
}
// Do excel export
}
catch (Exception e1)
{
MessageBox.Show("error");
}
}