Best way to fill DataGridView with large amount of data
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
I think you can use DataReader method instead of DataAdapter. DataReader is very efficient oneway component, because it's only reading data from the source, and you can fill a data table with looping.
If you have a huge amount of rows, like 10 000 and more,
to avoid performance leak - do the following before data binding:
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
//or even better .DisableResizing.
//Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dataGridView1.RowHeadersVisible = false; // set it to false if not needed
after data binding you may enable it.