Adding rows to DataGridView: Why so slow?

Peter King

Member
Joined
Sep 11, 2006
Messages
15
Programming Experience
Beginner
Hi,

I try to read in a text file (delimited with blank space) and display the data in a DataGridView. The problem is that the file is large, with 100000 lines and each line has 10 values separated by space. I use readline to read each line and populate a row in DataGridView, with code like this:

VB.NET:
Dim fsStream As New FileStream(ListViewFileName, _
FileMode.Open, FileAccess.Read)
Dim srReader As New StreamReader(fsStream)
For i As Integer = 0 To 100000
DataGridView1.Rows.Add(New String() {i, i, i, i, i, i, i, i, i, i})
If i Mod 10000 = 0 Then MsgBox(i)
Next


where LineString is the line read in from the text file and is in a 1-dimentional array format.

My problem is that it is extremely slow to load the file into the DataGridView. Do I miss something that can speed up? I know in ListView, one can use ListView.beginUpdate() before loading data to speed up, but cannot find an equivalent for DataGridView.

Alternatively, is it possible to bind the text file to DataGridView? If yes, does it speed up loading data into DataGridView?

Please help!

peter
 
I have deleted your other duplicate thread. I also included the code snippet from your other post in this one as it seemed relavent. Please feel free to edit this post if you feel it doesn't convey your request to your satisfaction.
 
Never add one item at a time to a control. You should ALWAYS be using AddRange rather than Add. Create all the items and put them in an array, then add the whole array in one go.

As for binding, while you can bind all sorts of objects it is generally preferable to put your data into a DataTable and bind that. This is a relatively simple exercise:
VB.NET:
Dim lines As String() = IO.File.ReadAllLines("file path here")
Dim table As New DataTable

'Build table schema here by adding DataColumns.

Dim row As DataRow

For Each line As String In lines
    row = table.NewRow()
    row.ItemArray = line.Split()
    table.Rows.Add(row)
Next line

grid.DataSource = table
 
Back
Top