c# - 如何将 DataSource 转换为 List<T>?

标签 c# winforms datagridview casting datasource

我有以下在 DataGridView 上加载产品的方法

private void LoadProducts(List<Product> products)
{
    Source.DataSource = products;  // Source is BindingSource
    ProductsDataGrid.DataSource = Source;
}

现在我正试图将它们还给我以保存它们,如下所示。

private void SaveAll()
{
   Repository repository = Repository.Instance;
   List<object> products = (List<object>)Source.DataSource; 
   Console.WriteLine("Este es el número {0}", products.Count);
   repository.SaveAll<Product>(products);
   notificacionLbl.Visible = false;
}

但是我在这一行得到了一个InvalidCastException:

List<object> products = (List<object>)Source.DataSource;

那么如何将 DataSource 转换为 List?

最佳答案

您不能直接协变地转换为 List;

或者:

List<Product> products = (List<Product>)Source.DataSource;

或:

List<Object> products = ((List<Product>)Source.DataSource).Cast<object>().ToList();

关于c# - 如何将 DataSource 转换为 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14279977/

相关文章:

c# - 如何选择单元格的值?

C#: Datagridview 不显示数据

c# - 改变我的命名空间是一件好事还是必要的?

c# - 如何在 C# 中创建右键单击事件处理程序

C# WinForms,使用 FFmpeg 库播放视频

c# - 如何使用 C# 清除 DataGridView 中的行?

c# - 针对相同版本的 .NET 框架的随机数种子

c# - 如何使用 XmlWriter 将编码属性添加到除 utf-16 之外的 xml?

c# - 创建 HttpClient 帮助器方法的问题

c# - 在 C# 中访问 Excel 单元格值