[英]One-Way data binding of a DataGridView to list of objects
I know there are many similar questions and I spent a lot of time looking at possible solutions. 我知道有很多类似的问题,因此我花了很多时间寻找可能的解决方案。 But I'm still not sure what's the easiest way to do it.
但是我仍然不确定最简单的方法是什么。
The goal is to show LogItems
(timestamp, severity level, message) in a DataGridView
sorted by their timestamp and allowing the user to filter the items by severity level. 目标是在
DataGridView
按时间戳记排序的LogItems
(时间戳记,严重性级别,消息),并允许用户按严重性级别筛选项目。
Here is exactly what I (don't) need: 这正是我(不需要)的需求:
DataGridView
to a list/collection of objects. DataGridView
与对象列表/集合的单向数据绑定。 No need to edit the objects via DataGridView
or to add/remove objects via DataGridView
by the user. DataGridView
或通过添加/删除对象DataGridView
用户。 But the DataGridView
should automatically update when I add or remove objects to that underlying list/collection. DataGridView
应该会自动更新。 DateTime
) and should be displayed ordered by this timestamp. DateTime
),并且应按此时间戳排序显示。 I don't care if the list itself keeps them sorted (something like SortedList<T>
would be nice, but it doesn't exist) or if the DataGridView
or a BindingSource
takes care of the sorting. SortedList<T>
会很好,但它不存在)还是DataGridView
或BindingSource
负责排序。 No need for the user to set up sorting by clicking on the column headers. Here some approaches I came up with: 在这里,我想出了一些方法:
BindingList<T>
as the underlying collection doesn't work since it doesn't support sorting and filtering. BindingList<T>
因为基础集合不起作用,因为它不支持排序和过滤。 BindingSource
doesn't help if the underlying collection doesn't support sorting and filtering. BindingSource
封装某些集合将无济于事。 IBindingListView
. IBindingListView
的自定义集合。 This looks quite complicated and I need only a subset of the features that IBindingListView
provides. IBindingListView
提供的功能的子集。 And I'm too lazy. BindingListView
sourceforge project . BindingListView
sourceforge项目 。 This is probably too heavy for what I need and I don't want to rely on third party libraries if I don't have to. What would be a simple and fast solution for this? 一个简单,快速的解决方案是什么?
I'd recommend to use a DataTable. 我建议使用DataTable。 You'll get all you need.
您将获得所需的一切。
Just make the DataGridView ReadOnly to prevent user editing. 只需将DataGridView设为ReadOnly即可防止用户编辑。 it will still update when the underlying DataTable is updated.
当基础DataTable更新时,它仍然会更新。
Cheers 干杯
Using a DataTable
would be an option, but in the end I decided to use the BindingListView
from sourceforge instead and I'm very happy with it. 使用
DataTable
是一种选择,但是最后我决定改用sourceforge的BindingListView
,对此我感到非常满意。
The problem with the DataTable
approach is that it would require to copy all the data from my custom objects into a DataTable
just for displaying. DataTable
方法的问题在于,它将需要将所有数据从我的自定义对象复制到DataTable
,以进行显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.