使用大量数据填充DataGridView的最佳方式 [英] Best way to fill DataGridView with large amount of data
问题描述
基本上有3种方式可以在 DataGridView
/ p>
-
在循环中手动创建行,正如您所注意到的那样,如果您有一个很多数据
-
根据Jonathan在评论中的建议,使用
DataGridView
的虚拟模式DGV只创建可以显示的行数,并在用户滚动时动态地更改其内容。您需要处理CellValueNeeded
事件,以向DGV提供所需的数据 -
使用数据绑定:到目前为止最简单的方法。您只需使用
DbDataAdapter
从数据库中填入DataTable
,并分配此DataTable
到DGV的DataSource
属性。 DGV可以自动创建列(AutoGenerateColumns = true
),或者您可以手动创建它们(您必须设置DataPropertyName
的列到要显示的字段的名称)。在数据绑定模式下,DGV的工作方式类似于虚拟模式,除了它负责从数据源获取数据,因此您无需做任何事情。即使是大量行也很有效
I have a windows form that has two DataGridViews (DGVs) that will hold 25,000+ records and 21 columns each. I have successfully loaded each with the data from the DB using a DataAdapter and then I tried simply filling the DGVs using for loops. Each method took roughly the same amount of time. The first time the data is filled into the DGVs it takes too long (7+ mins), and then the subsequent times the time is much more reasonable (~30 secs). So my question is, what is the best way to load a DGV with a large amount of data that will take on average <= 1 min? I really like the functionality of DGVs, but if push comes to shove I am willing to use a different technology, even if it means giving up some of that functionality.
There are basically 3 ways to display data in a DataGridView
Create the rows manually in a loop, as you are currently doing: as you have noticed, it's very inefficient if you have a lot of data
Use the
DataGridView
's virtual mode, as suggested by Jonathan in his comment: the DGV only creates as many rows as can be displayed, and dynamically changes their contents when the user scrolls. You need to handle theCellValueNeeded
event to provide the required data to the DGVUse databinding: that's by far the easiest way. You just fill a
DataTable
with the data from the database using aDbDataAdapter
, and you assign thisDataTable
to the DGV'sDataSource
property. The DGV can automatically create the columns (AutoGenerateColumns = true
), or you can create them manually (you must set theDataPropertyName
of the column to the name of the field you want to display). In databound mode, the DGV works like in virtual mode except that it takes care of fetching the data from the datasource, so you don't have anything to do. It's very efficient even for a large number of rows
这篇关于使用大量数据填充DataGridView的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!