通用DataGridView填充方法实现:如何适配自定义类?
实现通用DataGridView填充方法
要适配自定义类,你需要用泛型方法保留数据的具体类型信息,避免丢失类型导致SortableBindingList无法正确实例化。以下是完整实现:
通用方法代码
public static void FillDataGridView<T>(DataGridView dg, IEnumerable<T> data) where T : class { // 清空原有数据源 dg.DataSource = null; // 实例化对应类型的SortableBindingList var sortableList = new SortableBindingList<T>(data.ToList()); // 设置新数据源 dg.DataSource = sortableList; }
关键说明
- 泛型参数
T会自动匹配你传入的自定义类(比如Parts),无需手动指定类型; where T : class约束确保T是引用类型,符合SortableBindingList的实例化要求;- 调用时直接传入DataGridView控件和数据集合即可,无需额外类型转换。
调用示例
替换你原来的代码:
var items = partRepositiory.GetAllParts().ToList(); FillDataGridView(dgEinkaufsartikel, items);
这样无论你用Parts还是其他自定义实体类,这个方法都能直接复用。
内容的提问来源于stack exchange,提问作者Jocelyn
相关产品推荐
相关产品推荐

