c# - observablecollection 到 dataView 或 dataset

标签 c# wpf mvvm datagrid observablecollection

我有一个通过绑定(bind)observablecollection形成的Datagrid,现在我想提供导出到excel的功能,所以我需要通过datagrid转换为dataset或dataview。

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 包含基类和后端实体类

最佳答案

您需要使用所需的列手动创建数据表。我假设这些列是 DataSourceVM 类的属性。

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");
    }
}

关于c# - observablecollection 到 dataView 或 dataset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30499282/

相关文章:

c# - 行的WPF DataGrid StyleSelector

c# - NPOI中如何枚举excel工作表

c# - .NET - 如何正确设置函数的 Azure 服务总线队列/主题

c# - WPF 在单独的 UI 线程上加载动画? (C#)

c# - 打印时始终未选中 WPF 复选框

wpf - ViewModel中的INotifyPropertyChanged与DependencyProperty

WPF + 使用 MVVM 的上下文菜单项的绑定(bind)命令和标题

c# - 如何将逗号分隔的列值与另一个表作为行连接

c# - 在 Docker 上运行 Asp Core MVC - 静态文件/wwwroot 文件未加载

WPF 弹出窗口自动关闭