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 DGV -
Use 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